"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDomainByRegion = exports.getDomainByCountryCode = exports.setDomainByCountryCode = exports.sendRequest = void 0;
const crypto_1 = __importDefault(require("crypto"));
const axios_1 = __importDefault(require("axios"));
const store_1 = require("../store");
function getSeq() {
    return `${Date.now()}`;
}
function getAuthSign(seq, deviceId) {
    const apiKey = store_1.getApiKey();
    const toEncryptStr = `${apiKey}_${deviceId}_${seq}`;
    let sign = '';
    if (store_1.getDebug()) {
        console.log(`authorization sign:\n${toEncryptStr}\n\n`);
    }
    sign = crypto_1.default.createHash('sha256').update(toEncryptStr).digest('hex');
    return sign;
}
function sendRequest(url, method, params, at) {
    return __awaiter(this, void 0, void 0, function* () {
        const config = {
            url,
            method,
            baseURL: store_1.getDomain(),
            headers: {},
            timeout: store_1.getTimeout(),
        };
        const seq = getSeq();
        const deviceId = store_1.getDeviceId();
        const isDevice = store_1.getIsDevice();
        config.headers['X-CK-Seq'] = seq;
        config.headers['X-CK-Deviceid'] = deviceId;
        if (at) {
            config.headers['Authorization'] = `Bearer ${at}`;
        }
        else {
            config.headers['Authorization'] = `Sign ${getAuthSign(seq, deviceId)}`;
        }
        if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
            config.headers['Content-Type'] = 'application/json';
        }
        if (method === 'GET' && params) {
            config.params = params;
        }
        else if (params) {
            config.data = params;
        }
        if (store_1.getDebug()) {
            console.log(`axios config:\n${JSON.stringify(config, null, 4)}\n\n`);
        }
        try {
            const res = yield axios_1.default(config);
            if (store_1.getDebug()) {
                console.log(`axios response:\n${JSON.stringify(res.data, null, 4)}\n\n`);
            }
            if (res.data.error === 10004) {
                store_1.setDomain(getDomainByRegion(res.data.data.region, isDevice));
                return yield sendRequest(url, method, params, at);
            }
            return res.data;
        }
        catch (e) {
            console.log(e);
            return {
                error: 500,
                msg: 'axios error',
                data: {},
            };
        }
    });
}
exports.sendRequest = sendRequest;
function setDomainByCountryCode(code) {
    const isDevice = store_1.getIsDevice();
    const domain = getDomainByCountryCode(code, isDevice);
    console.log(`SL : file: index.ts : line 102 : setDomainByCountryCode : domain`, domain);
    if (domain === '') {
        return false;
    }
    else {
        store_1.setDomain(domain);
        return true;
    }
}
exports.setDomainByCountryCode = setDomainByCountryCode;
function getDomainByCountryCode(region, isDevice) {
    const useTestEev = store_1.getUseTestEev();
    console.log(`SL : file: index.ts : line 119 : getDomainByCountryCode : useTestEev`, useTestEev);
    if (useTestEev) {
        return `https://test-${isDevice ? 'apid' : 'apia'}.coolkit.cn`;
    }
    return getDomainByRegion(region, isDevice);
}
exports.getDomainByCountryCode = getDomainByCountryCode;
function getDomainByRegion(region, isDevice) {
    return `https://${region}-${isDevice ? 'apid' : 'apia'}.coolkit.${region === 'cn' ? 'cn' : 'cc'}`;
}
exports.getDomainByRegion = getDomainByRegion;
