// 加载时的三个缓存，和 generator 的缓存有点像，所以暂时放在这里
import { config, WebService, MicroService, View, utils } from '..';
import { loadCacheService } from '../../service/webFile';
import { ServiceType } from '../../service/common/preprocess';

/**
 * 生成接口列表缓存
 */
export function saveInterfacesCache(service: MicroService) {
    if (!config.initialLoadCache)
        return;

    const timestamp = +new Date();
    const json: Array<any> = [];

    service.interfaces.forEach((item) => {
        const itface = item.toJSON();
        itface.serviceType = (ServiceType as any)[itface.serviceType] || itface.serviceType;
        itface._cacheTimestamp = timestamp;

        // 目前 interface 下不会自动生成 logic
        const logic = item.logic.toJSON();
        logic.body = null;
        logic.serviceType = (ServiceType as any)[logic.serviceType];
        itface.logic = logic;
        json.push(itface);
    });

    return loadCacheService.setCache({
        body: {
            type: 'INTERFACE_LIST',
            key: service.id,
            data: JSON.stringify(json),
            timestamp: +new Date(),
        },
    });
}

export function savePageTreeCache(service: WebService) {
    if (!config.initialLoadCache)
        return;

    const timestamp = +new Date();
    const json: Array<any> = [];

    service.pages.forEach((item) => {
        const page = item.toJSON();
        page._cacheTimestamp = timestamp;
        utils.traverse((current) => {
            if (current.node.level === 'view') {
                const viewJson = current.node;
                viewJson.$html = null;
                viewJson.$def.logics.forEach((logic: any) => {
                    logic.body = null;
                });
            }
        }, { node: page }, { mode: 'anyObject' });
        json.push(page);
    });

    return loadCacheService.setCache({
        body: {
            type: 'PAGE_LIST',
            key: service.id,
            data: JSON.stringify(json),
            timestamp: +new Date(),
        },
    });
}

export function saveViewDetailCache(view: View) {
    if (!config.initialLoadCache)
        return;

    const timestamp = +new Date();
    const json = view.toJSON('', ['children']);
    delete json.children;
    json._cacheTimestamp = timestamp;

    return loadCacheService.setCache({
        body: {
            type: 'PAGE_DETAIL',
            key: view.id,
            data: JSON.stringify(json),
            timestamp: +new Date(),
        },
    });
}

export function clearLoadCache(type: string, key: string) {
    return loadCacheService.clearCache({
        query: {
            type,
            key,
        },
    });
}
