"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
exports.downloadPackage = exports.uploadPackage = exports.getUserInfo = exports.getConnectDevServerWebSocketCode = void 0;
var axios_1 = __importDefault(require("axios"));
var storage_1 = require("../storage");
var project_1 = require("../config/project");
var logger_1 = require("../logger");
var loginStorageKey = (0, project_1.getLocalConfig)().loginStorageKey;
var getConnectDevServerWebSocketCode = function () { return __awaiter(void 0, void 0, void 0, function () {
    var _a, _subRegionalHost, _b, _loginAppToken, thisUrl, url, error_1, message;
    var _c, _d;
    return __generator(this, function (_e) {
        switch (_e.label) {
            case 0:
                if (!process.env._subRegionalHost) {
                    storage_1.globalStorage.deleteStorage(loginStorageKey.accountToken);
                    throw new Error('401');
                }
                _e.label = 1;
            case 1:
                _e.trys.push([1, 3, , 4]);
                _a = process.env, _subRegionalHost = _a._subRegionalHost, _b = _a._loginAppToken, _loginAppToken = _b === void 0 ? '' : _b;
                thisUrl = "https://".concat(_subRegionalHost, "/developerbridge/client/relay");
                return [4, axios_1["default"].get(thisUrl, {
                        headers: {
                            apptoken: _loginAppToken
                        }
                    })];
            case 2:
                url = (_e.sent()).data.url;
                return [2, url];
            case 3:
                error_1 = _e.sent();
                message = (error_1 === null || error_1 === void 0 ? void 0 : error_1.response) && ((_c = error_1.response) === null || _c === void 0 ? void 0 : _c.data);
                if ((message === null || message === void 0 ? void 0 : message.code) === 401 && ((_d = message === null || message === void 0 ? void 0 : message.data) === null || _d === void 0 ? void 0 : _d.code) === '0102') {
                    storage_1.globalStorage.deleteStorage(loginStorageKey.accountToken);
                    throw new Error('401');
                }
                else {
                    process.env._bridgeOptionalDevice = '';
                    process.env._bridgeChoiredDevice = '';
                    throw new Error("GetConnectDevServerWebSocketCode error");
                }
                return [3, 4];
            case 4: return [2];
        }
    });
}); };
exports.getConnectDevServerWebSocketCode = getConnectDevServerWebSocketCode;
var getUserInfo = function (url, token) { return __awaiter(void 0, void 0, void 0, function () {
    var headers, userInfo, data, error_2, message;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                headers = {
                    apptoken: token,
                    'Content-Type': 'application/json'
                };
                _a.label = 1;
            case 1:
                _a.trys.push([1, 3, , 4]);
                return [4, axios_1["default"].get(url, {
                        headers: headers
                    })];
            case 2:
                userInfo = _a.sent();
                data = userInfo.data;
                return [2, data];
            case 3:
                error_2 = _a.sent();
                message = typeof error_2 === 'object' ? error_2.message : error_2;
                if (message.includes('401')) {
                    storage_1.globalStorage.deleteStorage(loginStorageKey.accountToken);
                    throw new Error('401');
                }
                throw new Error('get nickName error');
            case 4: return [2];
        }
    });
}); };
exports.getUserInfo = getUserInfo;
var uploadPackage = function (form, length) { return __awaiter(void 0, void 0, void 0, function () {
    var _a, _subRegionalHost, _b, _loginAppToken, _loginUserId, packageInfo, _c, protocol, code, error_3, message;
    return __generator(this, function (_d) {
        switch (_d.label) {
            case 0:
                _a = process.env, _subRegionalHost = _a._subRegionalHost, _b = _a._loginAppToken, _loginAppToken = _b === void 0 ? '' : _b, _loginUserId = _a._loginUserId;
                _d.label = 1;
            case 1:
                _d.trys.push([1, 3, , 4]);
                return [4, axios_1["default"].post("https://".concat(_subRegionalHost, "/custom/tools/app-dial/upload?userid=").concat(_loginUserId), form, {
                        headers: __assign(__assign({}, form.getHeaders()), { 'content-length': "".concat(length), apptoken: _loginAppToken }),
                        maxContentLength: Infinity,
                        maxBodyLength: Infinity
                    })];
            case 2:
                packageInfo = _d.sent();
                _c = (packageInfo === null || packageInfo === void 0 ? void 0 : packageInfo.data) || {}, protocol = _c.protocol, code = _c.code;
                return [2, { protocol: protocol, code: code }];
            case 3:
                error_3 = _d.sent();
                message = typeof error_3 === 'object' ? error_3.message : error_3;
                if (message.includes('401')) {
                    storage_1.globalStorage.deleteStorage(loginStorageKey.accountToken);
                    throw new Error('401');
                }
                throw new Error(message);
            case 4: return [2];
        }
    });
}); };
exports.uploadPackage = uploadPackage;
var downloadPackage = function (code, deviceSource, appType) { return __awaiter(void 0, void 0, void 0, function () {
    var _a, _subRegionalHost, _b, _loginAppToken, _loginUserId, host, packageInfo, error_4, message;
    return __generator(this, function (_c) {
        switch (_c.label) {
            case 0:
                _c.trys.push([0, 2, , 3]);
                _a = process.env, _subRegionalHost = _a._subRegionalHost, _b = _a._loginAppToken, _loginAppToken = _b === void 0 ? '' : _b, _loginUserId = _a._loginUserId;
                host = "https://".concat(_subRegionalHost, "/custom/tools/app-dial/download/").concat(code);
                if (appType === 'app') {
                    return [2, host];
                }
                return [4, axios_1["default"].get("".concat(host, "?userid=").concat(_loginUserId, "&deviceSource=").concat(deviceSource), {
                        headers: {
                            apptoken: _loginAppToken
                        }
                    })];
            case 1:
                packageInfo = _c.sent();
                return [2, packageInfo];
            case 2:
                error_4 = _c.sent();
                message = typeof error_4 === 'object' ? error_4.message : error_4;
                if (message.includes('401')) {
                    storage_1.globalStorage.deleteStorage(loginStorageKey.accountToken);
                    message = "Invalid token,please login again with the command 'zeus login'.";
                }
                logger_1.logger.error(message);
                return [3, 3];
            case 3: return [2];
        }
    });
}); };
exports.downloadPackage = downloadPackage;
