import { Singleton, Container, Scope, Inject } from "typescript-ioc";
import * as schedule from 'node-schedule'
import { logger, OpResult } from 'mslib'

/**
 * K8S配置缓存
 * @date 2021-09-13 13:39:31
 * @author 吴锋霖
 */
@Singleton
class K8SConfigCache {


    private cacheMap = new Map<string, K8SPrmsConfig>();

    private clusterIdCacheMap = new Map<string, string>()

    /**
     * 示例函数fun1
     * @param cloudType 0:阿里云,1:华为云
     */
    async init(cloudType: string): Promise<any> {
        try {
            schedule.scheduleJob('0 30 * * * *', async () => {
                try {
                    await this.reloadCache(cloudType)
                } catch (e) {
                    logger.error('刷新K8S客户端缓存异常', e)
                }
            });

            await this.reloadCache(cloudType)
        } catch (e) {
            logger.error('刷新K8S客户端缓存异常', e)
        }
    }

    private async reloadCache(cloudType: string) {
        // const op = await k8sClusterQueryList({ rawCondition: `cloud_provider='${cloudType}'` })
        // const data = op.data
        const data = [
            {
                id:'81a23c8a12214af3b8d329ab03f155f1',
                name:'非标华为云-生产',
                jsonConfig:JSON.stringify({'prmsUrl':'http://119.3.154.174:9090/','clusterId':'4cda12a0-28d5-11ed-bdcd-0255ac1000c8'}) ,
                cloudProvider:'1'
            }
        ]
        for (let row of data) {
            if (this.cacheMap.has(row.id)) {
                continue;
            }
            logger.info('准备初始化K8S客户端--------->%s', row.name)
            const k8sConfig = JSON.parse(row.jsonConfig)

            const config: K8SPrmsConfig = {
                id: k8sConfig.clusterId,
                name: row.name,
                cloudProvider: cloudType === '0' ? 'ALIYUN' : 'HUAWEI',
                apiUrl: k8sConfig.apiAddress,
                prmsUrl: k8sConfig.prmsUrl
            }

            this.cacheMap.set(row.id, config)
            this.clusterIdCacheMap.set(k8sConfig.clusterId, row.id)
            logger.info('初始化K8S客户端完成--------->%s', row.name)

        }
    }


    /**
     * 获取K8S API客户端
     */
    getClient(id: string): K8SPrmsConfig {
        return this.cacheMap.get(id)
    }


    /**
     * 通过集群ID获取K8S记录主键
     */
    getIdByClusterId(clusterId: string): string {
        return this.clusterIdCacheMap.get(clusterId)
    }


    /**
     * 获取K8S API客户端
     */
    getAllClients(): Array<K8SPrmsConfig> {
        return Array.from(this.cacheMap.values())
    }

}

export class K8SPrmsConfig {
    id: string
    name: string
    cloudProvider: string
    apiUrl: string
    prmsUrl: string
}

export { K8SConfigCache }