import Cache from './cache';

import instructions from '../instructions/index';

const cache = new Cache();

import {
    InstructionsWhere,
    InstructionsTypes,
    LibRequestStatus,
    InstructionsCacheSync
} from '../const/request';

instructions.push('cache',{
    trigger:function (data: LibRequestContext) {

        let sign:string = data.sign ? data.sign : Cache.sign(data.requestData);

        if (!data.sign) {
            data.sign = sign;
        }

        // 如果为请求触发
        if (data.status === LibRequestStatus.loading || data.status === LibRequestStatus.fail) {

            let resultData = cache.getCache(sign);

            // @ts-ignore
            if (resultData !== undefined && resultData.data && (typeof data.requestData.cache === 'boolean' || data.requestData.cache.updated !== true)) {
                data.responseData = JSON.parse(JSON.stringify(resultData.data));
                // 设置本次属于缓存
                // @ts-ignore
                data.responseData.data.isCache = true;

                data.status = LibRequestStatus.success;

                let storageCache = data.requestData.cache;

                delete data.requestData.cache;

                instructions.trigger(data,InstructionsTypes.end);

                if (
                    data.status === LibRequestStatus.fail
                    ||
                    !(
                        // @ts-ignore
                        resultData.first && (typeof storageCache === 'boolean' || storageCache.sync === InstructionsCacheSync.first )
                        ||
                        // @ts-ignore
                        typeof storageCache!== 'boolean' && typeof storageCache.sync=== 'function' && storageCache.sync(resultData,data)
                    )
                ) {

                    // 退出本次执行
                    // @ts-ignore
                    return  data.exit('cache',false);
                } else {
                    data.requestData.cache = storageCache;
                }

            }

        } else{

            let resultData:InstructionsCache;
            if (typeof data.requestData.cache === 'boolean') {
                resultData = {};
            } else {
                resultData = {...data.requestData.cache};
            }

            // @ts-ignore
            if (resultData.where === undefined && data.responseData.data.isSuccess || typeof resultData.where === 'function' && resultData.where(resultData,data)) {
                // 存储必要参数
                resultData.data = {
                    // @ts-ignore
                    statusCode: data.responseData.status,
                    // @ts-ignore
                    data: JSON.parse(JSON.stringify(data.responseData.data))
                };


                return cache.setCache(sign,resultData);
            }

        }

    },
    triggerType:InstructionsTypes.all,
    zIndex:-8,
    where:InstructionsWhere.has
});


export {
    cache
}