import { Singleton, Container, Scope, Inject } from "typescript-ioc";
import * as schedule from 'node-schedule'
import { k8sClusterQueryList } from '../refs/mms-dao'
import { logger } from 'mslib'
import { ApiClient, Config as K8SConfig } from '../refs/k8s-api';

/**
 * K8S客户端工厂
 * @date 2021-05-27 10:41:41
 * @author 吴锋霖
 */
@Singleton
class K8SClientFactory {


    private k8sIdClientMap = new Map<string, ApiClient>()

    /**
     * 示例函数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
        for (let row of data) {
            if (this.k8sIdClientMap.has(row.id)) {
                continue;
            }
            logger.info('准备初始化K8S客户端--------->%s', row.name)
            const k8sConfig = JSON.parse(row.jsonConfig)

            const config: K8SConfig = {
                id: k8sConfig.clusterId,
                name: row.name,
                cloudProvider: cloudType === '0' ? 'ALIYUN' : 'HUAWEI',
                apiUrl: k8sConfig.apiAddress,
                ca: k8sConfig.ca,
                cc: k8sConfig.cc,
                ck: k8sConfig.ck,
                defaultImagePullSecret: 'vpcregsecret',
                defaultStorage: 20,
                defaultStorageClassName: cloudType === '0' ? 'alicloud-disk-available' : ''
            }
            const client = new ApiClient(config)
            this.k8sIdClientMap.set(row.id, client)
            logger.info('初始化K8S客户端完成--------->%s', row.name)

        }
    }


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


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

export { K8SClientFactory }