'use strict';

const axios = require('axios');
const log = require('electron-xlog');

module.exports = {
    _domain: "https://yun.tim.qq.com/v4/ilvb_edu",
    _sdk_app_id: 0,
    _user_id: '',
    _user_sig: '',
    _module_map: {},
    _last_report_time: 0,
    _heartbeat_version: "1.0",
    _heartbeat_interval: 30,         // 默认为30秒间隔
    _heartbeat_timer: null,
    rsp_callback: null,

    /** 对外接口 */
    init: function(debug, sdkAppId, userId, userSig, rspCallback, lastReportTime){
        if (debug){
            this._domain = "https://yun.tim.qq.com/v4/ilvb_test";
        }else{
            this._domain = "https://yun.tim.qq.com/v4/ilvb_edu";
        }
        this._sdk_app_id = sdkAppId;
        this._user_id = userId;
        this._user_sig = userSig;
        this._rsp_callback = rspCallback;
        this._last_report_time = lastReportTime;
    },
    updateModule: function(type, sub, data=null){        // 添加/更新模块信息
        var moduleKey = type+"_"+sub;
        this._module_map[moduleKey] = {
            BusinessType: type,
            Submodule: sub
        }
        if (data){
            this._module_map[moduleKey].CustomData = data;
        }
    },
    updateHeartbeat: function(reportNow = true){    // 更新/补发心跳
        if (!this._heartbeat_timer){
            this._heartbeat_timer = setInterval(()=>{
                this._reportBeat();
            }, (this._heartbeat_interval*1000));
        }
        if (reportNow){
            this._reportBeat();
        }        
    },
    getLastReportTime: function(){      // 获取上次心跳间隔
        return this._last_report_time;
    },
    removeModule: function(type, sub){      // 移除模块
        var moduleKey = type+"_"+sub;
        delete this._module_map[moduleKey];
    },
    exit: function(){
        this._removeTimer();
    },

    /** 内部接口 */
    _removeTimer: function(){        // 移除心跳
        if (null != this._heartbeat_timer){
            clearInterval(this._heartbeat_timer);
            this._heartbeat_timer = null;
        }
    },

    _reportBeat: function(){     // 上报心跳
        var list = [];
        for (var k in this._module_map){
            list.push(this._module_map[k]);
        }
        var data = JSON.stringify({
            HeartbeatList: list,
            LastReportTime: this._last_report_time,
            HeartbeatVersion: this._heartbeat_version
        });
        var reqUrl = this._domain + "/report_heartbeat?sdkappid="+this._sdk_app_id+"&identifier="+this._user_id+"&usersig="
            +this._user_sig+"&random="+Math.floor(Math.random()*10000)+"&contenttype=json";

        log.info("[TAG-HEARTBEAT] _reportBeat->url:"+reqUrl);
        log.info("[TAG-HEARTBEAT] _reportBeat->req:"+data);

        this._post({url: reqUrl, data: data}, (ret, json)=>{
            if (ret){
                if (json.ErrorCode && json.ErrorCode == 70001){
                    this._rsp_callback("error", json.ErrorCode, json.ErrorInfo);
                    return;
                }
                this._last_report_time = json.Response.ReportTime;
                if (this._heartbeat_interval != json.Response.IntervalTime){
                    this.removeTimer();
                    this._heartbeat_interval = json.Response.IntervalTime;
                    this.updateHeartbeat(false);                    
                }
                if (null != this._rsp_callback){
                    this._rsp_callback("common", "", this._last_report_time);
                    if (null != json.Response.BusinessRsp){
                        for (var i=0; i<json.Response.BusinessRsp.length; i++){
                            this._rsp_callback(json.Response.BusinessRsp[i].BusinessType, json.Response.BusinessRsp[i].Submodule, json.Response.BusinessRsp[i].Rsp);
                        }
                    }                    
                }
            }
        }, "reportBeat")
    },

    _post: function(option, callback, name="post"){
        option.headers = {"Content-Type": "application/json"};
        option.method = "POST";
        axios(option).then((rsp)=>{
            log.info("[TAG-HEARTBEAT] "+name+"->rsp: "+JSON.stringify(rsp.data, null, 2));
            callback(true, rsp.data);
        }).catch((err)=>{
            log.error("[TAG-HEARTBEAT] "+name+"->fail: "+err.stack);
            callback(false, err.message);
        })
    }
}