"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchSwitchTenant = exports.getTenantList = exports.getUserId = void 0;
const core_1 = require("../../core");
const utils_1 = require("../../core/libs/utils/utils");
const Error_1 = __importStar(require("../../core/libs/common/Error"));
const base_1 = __importDefault(require("./base"));
const getUserId = (manager, tenantList) => {
    return manager.execute(core_1.ModuleName.ui, core_1.UICmdEnum.pick, tenantList.map((item) => ({
        name: item.tenant.name,
        value: item.user.id,
    })), 'Choose a tenant to switch');
};
exports.getUserId = getUserId;
const getTenantList = async (manager) => {
    return ((await manager.execute(core_1.ModuleName.account, core_1.AccountCmdEnum.tenantList)) || []);
};
exports.getTenantList = getTenantList;
const fetchSwitchTenant = (manager, account) => {
    return new Promise((resolve) => {
        manager
            .execute(core_1.ModuleName.account, core_1.AccountCmdEnum.switchTenant, account)
            .then((res) => {
            if (res.result === 'success') {
                resolve(true);
            }
            else {
                resolve(false);
            }
        });
    });
};
exports.fetchSwitchTenant = fetchSwitchTenant;
class Account extends base_1.default {
    constructor() {
        super(core_1.ModuleName.account);
    }
    isLogin(environment) {
        return this.manager.execute(core_1.ModuleName.account, core_1.AccountCmdEnum.IsLogin, environment);
    }
    getAccountInfo(environment) {
        const accountInfo = this.manager.execute(core_1.ModuleName.account, core_1.AccountCmdEnum.Info, environment);
        return accountInfo;
    }
    getUserInfo() {
        const accountInfo = this.getAccountInfo();
        if (!accountInfo) {
            return '';
        }
        const { larkSession, env } = accountInfo;
        const automationToken = (0, utils_1.base64Encode)(`${env}${utils_1.AccountSplitsDefine}${larkSession}`);
        return `
  - Environment: ${env}
  - User：${accountInfo.user.display_name || accountInfo.user.name}
  - Tenant：${accountInfo.tenant.name}
  - Automation-Token: ${automationToken}`;
    }
    async login(options) {
        if (this.isLogin(options.environment)) {
            const accountInfo = this.getAccountInfo(options.environment);
            if (!accountInfo) {
                throw new Error('login failed, accountInfo not found');
            }
            return accountInfo;
        }
        await new Promise((resolve) => {
            this.manager.addEventListener(core_1.ModuleName.account, core_1.AccountEventEnum.Logined, () => {
                resolve();
            });
            this.manager.execute(core_1.ModuleName.account, core_1.AccountCmdEnum.Login, {
                showSuccessPage: true,
                environment: options.environment,
                skipConfirm: true,
            });
        });
        const accountInfo = this.getAccountInfo(options.environment);
        if (!accountInfo) {
            throw new Error('login failed, accountInfo not found');
        }
        return accountInfo;
    }
    logout(options) {
        return new Promise((resolve) => {
            this.manager.addEventListener(core_1.ModuleName.account, core_1.AccountEventEnum.Logouted, () => {
                resolve();
            });
            this.manager.execute(core_1.ModuleName.account, core_1.AccountCmdEnum.Logout, options);
        });
    }
    getTenantList() {
        return (0, exports.getTenantList)(this.manager);
    }
    async switchTenant() {
        if (this.isLogin()) {
            this.loading('Loading your tenants');
            const tenantList = (await this.getTenantList()).filter((t) => t.tenant.isLogin);
            if (tenantList.length) {
                const spinner = this.loading('');
                if (spinner) {
                    spinner.stop();
                }
                const accountInfo = this.manager.execute(core_1.ModuleName.account, core_1.AccountCmdEnum.Info);
                if (tenantList.length === 0) {
                    this.manager.execute(core_1.ModuleName.ui, core_1.UICmdEnum.showInfo, {
                        content: 'No tenant can switch',
                    });
                    return;
                }
                const userId = await (0, exports.getUserId)(this.manager, tenantList);
                if (userId === (accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.user.id)) {
                    this.manager.execute(core_1.ModuleName.ui, core_1.UICmdEnum.showInfo, {
                        content: `Success switch to ${accountInfo.tenant.name}`,
                    });
                    return;
                }
                const switchedAccount = tenantList.find((item) => item.user.id === userId);
                if (switchedAccount) {
                    const switchSuccess = await (0, exports.fetchSwitchTenant)(this.manager, switchedAccount);
                    if (switchSuccess) {
                        this.manager.execute(core_1.ModuleName.ui, core_1.UICmdEnum.showInfo, {
                            content: `Success switch to ${switchedAccount.tenant.name}`,
                        });
                    }
                    else {
                        throw new Error_1.default({
                            code: Error_1.CoreErrorCode.CORE_MODULE_ERROR,
                            message: core_1.i18nHelper.t('SWITCH_TENANT_FAIL', {
                                tenant: switchedAccount.tenant.name,
                            }),
                        });
                    }
                }
            }
        }
        else {
            this.manager.execute(core_1.ModuleName.ui, core_1.UICmdEnum.showInfo, {
                content: 'Please Login First',
            });
            await this.login({});
            await this.switchTenant.bind(this)();
        }
    }
    switchEnv(options) {
        return new Promise((resolve) => {
            this.manager.addEventListener(core_1.ModuleName.account, core_1.AccountEventEnum.switchedEnv, () => {
                resolve();
            });
            this.manager.execute(core_1.ModuleName.account, core_1.AccountCmdEnum.switchEnv, {
                environment: options.environment,
            });
        });
    }
    static checkTokenExist(command) {
        if (process.env.OPDEV_TOKEN) {
            throw new Error_1.default({
                code: Error_1.CoreErrorCode.CORE_MODULE_ERROR,
                message: core_1.i18nHelper.t('COMMAND_DISABLE_ERROR', { command }),
            });
        }
    }
}
exports.default = Account;
