"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.revokeToken = exports.getTokens = exports.tokenCreate = void 0;
const base_1 = __importDefault(require("./base"));
const core_1 = require("../../core");
const api_1 = require("../../core/libs/config/api");
const terminal_kit_1 = require("terminal-kit");
const Error_1 = __importStar(require("../../core/libs/common/Error"));
const account_1 = __importDefault(require("./account"));
const tokenCreate = (manager, cidrs) => {
    return manager.execute(core_1.ModuleName.service, core_1.ServiceCmdEnum.Request, api_1.API.createToken, {
        cidr: cidrs,
    }, { responseCode: true });
};
exports.tokenCreate = tokenCreate;
const getTokens = (manager) => {
    return manager.execute(core_1.ModuleName.service, core_1.ServiceCmdEnum.Request, api_1.API.getTokens);
};
exports.getTokens = getTokens;
const revokeToken = (manager, token) => {
    return manager.execute(core_1.ModuleName.service, core_1.ServiceCmdEnum.Request, api_1.API.revokeToken, {
        token,
    }, { responseCode: true });
};
exports.revokeToken = revokeToken;
class Token extends base_1.default {
    constructor() {
        super([core_1.ModuleName.service, core_1.ModuleName.ui, core_1.ModuleName.eventTracker]);
    }
    async create(options) {
        let cidrs = [];
        if (options.cidr) {
            cidrs = options.cidr.split(',');
        }
        const result = await (0, exports.tokenCreate)(this.manager, cidrs);
        if (result.error) {
            throw new Error_1.default({
                code: Error_1.CoreErrorCode.REQUEST_ERROR,
                message: core_1.i18nHelper.t('TOKEN_CREATE_ERROR', { message: result.message }, 'Token created failed: {message}'),
            });
        }
        this.manager.execute(core_1.ModuleName.ui, core_1.UICmdEnum.showInfo, {
            content: `Token generated successfully:\n${result.data.token}`,
        });
    }
    async list() {
        const { tokens } = await (0, exports.getTokens)(this.manager);
        const tables = [['index', 'token', 'created', 'CIDR whitelist']];
        if (!tokens) {
            this.manager.execute(core_1.ModuleName.ui, core_1.UICmdEnum.showInfo, {
                content: 'No token',
            });
            return;
        }
        tokens
            .sort((a, b) => (a.createTime < b.createTime ? 1 : -1))
            .forEach((item, i) => {
            const date = new Date(item.createTime);
            tables.push([
                i,
                item.token,
                `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`,
                item.cidr ? item.cidr.join('\n') : '',
            ]);
        });
        terminal_kit_1.terminal.table(tables, {
            hasBorder: true,
            contentHasMarkup: true,
            borderChars: 'lightRounded',
            borderAttr: { color: 'grey' },
            firstRowTextAttr: { color: 'red' },
            width: 70,
            fit: true,
        });
    }
    async revoke(token) {
        const result = await (0, exports.revokeToken)(this.manager, token);
        if (result.error) {
            throw new Error_1.default({
                code: Error_1.CoreErrorCode.REQUEST_ERROR,
                message: core_1.i18nHelper.t('TOKEN_REVOKE_ERROR', {}, 'Token revoked failed'),
            });
        }
        this.manager.execute(core_1.ModuleName.ui, core_1.UICmdEnum.showInfo, {
            content: 'Token revoked successfully',
        });
    }
    checkLogin() {
        const account = new account_1.default();
        if (!account.isLogin()) {
            throw new Error_1.default({
                code: Error_1.CoreErrorCode.CORE_MODULE_ERROR,
                message: core_1.i18nHelper.t('NOT_LOGIN'),
            });
        }
    }
}
exports.default = Token;
