/**
 * 
 */

import { logger } from "mslib";
import { Singleton } from "typescript-ioc";
import { getBasicConfig, getNonStandardApiConfig } from "./Config";
import Contants from "./Contants";
const IORedis = require("ioredis");

const test_defaults = { host: 'r-bp1qmwd11yi1ujmfbq.redis.rds.aliyuncs.com', port: 6379, password: 'Keytop123', database: 50, maxRetriesPerRequest: 0, lazyConnect: true };
const prod_defaults = { host: 'r-bp117e21a00ae2e4.redis.rds.aliyuncs.com', port: 6379, password: 'Keytop123', database: 111, maxRetriesPerRequest: 0, lazyConnect: true };

let defaults = { maxRetriesPerRequest: 0, lazyConnect: true };

if (Contants.IS_PROD) defaults = prod_defaults;
else if (Contants.IS_TEST) defaults = test_defaults;

/**
 * 非标缓存运行时ioredis配置
 */
export const ioredisConfig = Object.assign(defaults, getNonStandardApiConfig()?.ioredis,
    {
        maxRetriesPerRequest: 0,
        lazyConnect: true,
        autoResendUnfulfilledCommands: false
    });

/**
 * ioredis 实例
 */
export const ioredisInstance = new IORedis(ioredisConfig);

ioredisInstance.on("error", error => {
    if (error.code === 'ECONNREFUSED') return;
    logger.error(error);
});

/**
 * 缓存键管理
 */
export class CacheKey {
    /**
     * app已授权车场配置信息key
     */
    static readonly CONFIG_INFO = `${getBasicConfig().tapdId}_configInfo`;
}

/**
 * 中台项目缓存服务
 */
@Singleton
export default class CacheService {
    async getConfigInfo() {
        return this.get(CacheKey.CONFIG_INFO);
    }

    setConfigInfoAsync(value, ex?: number) {
        this.setAsync(CacheKey.CONFIG_INFO, JSON.stringify(value), ex || 60 * 60);
    }

    async get(key) {
        try {
            return await ioredisInstance.get(key);
        } catch (error) {
            logger.error(`获取缓存失败，key:${key}`, error);
            return;
        }
    }

    setAsync(key, value, ex?: number) {
        setTimeout(async () => {
            try {
                await ioredisInstance.set(key, value, 'ex', ex);
            } catch (error) {
                logger.error(`设置缓存失败，args:${JSON.stringify(arguments)}`, error);
            }
        });
    }
}

export { CacheService }