import * as schedule from 'node-schedule'
import HttpUtil from "utils/HttpUtils";
import SignUtils from "utils/SignUtils";
import {logger} from "mslib/Logger"
import {EnvVariables} from "../mslib";
import {Container, Singleton} from 'typescript-ioc';
const signFunction = SignUtils.sign;

/**
 * 心跳定时任务
 */
@Singleton
export class HeartbeatTask {

    async start() {
        try {
            schedule.scheduleJob('30 * * * * *', this.sendMessage);
        } catch (e) {
            logger.error('心跳消息发送异常', e)
        }
        await this.sendMessage();
    }

    private async sendMessage() {
        try {
            if (!EnvVariables.getK8SId()) {//非K8S部署环境，不上报心跳
                return
            }
            if (EnvVariables.isDisabledHeartbeatTask()) {//非K8S部署环境，不上报心跳
                return
            }

            let serviceUrl = EnvVariables.getMasterRegisterUrl() + '/heartbeat';
            //有心跳上报地址，则通过该地址上报
            if (EnvVariables.getHeartbeatServiceUrl()) {
                serviceUrl = EnvVariables.getHeartbeatServiceUrl()
            }

            const headers = {
                'kt-k8s-id': EnvVariables.getK8SId(),
                'kt-deploy-id': EnvVariables.getDeployId(),
                'kt-me-env': EnvVariables.getEnvCode(),
                'kt-pod-id': EnvVariables.getPodId()
            }
            headers['kt-heartbeat-sign'] = SignUtils.sign(headers, EnvVariables.getEnvKey());

            const response = await HttpUtil.get(serviceUrl, {}, headers).catch(error => {
                logger.error('心跳消息上报异常--->' + error)
            });

            if (response && response.data.code === 5000) {
                logger.error('心跳消息上报失败--->headers:[%j] , response: %j', headers, response.data)
            }
        } catch (e) {
            logger.error('心跳消息发送异常', e)
        }
    }


}