"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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 });
const child_process_1 = __importDefault(require("child_process"));
const es6_promisify_1 = require("es6-promisify");
const fs_1 = __importDefault(require("fs"));
const inquirer_1 = require("inquirer");
const ora_1 = __importDefault(require("ora"));
const path_1 = __importDefault(require("path"));
const selfupdate_1 = __importDefault(require("selfupdate"));
const packageInfo = require('../../package');
const update = es6_promisify_1.promisify(selfupdate_1.default.update);
const isUpdated = es6_promisify_1.promisify(selfupdate_1.default.isUpdated);
const exec = es6_promisify_1.promisify(child_process_1.default.exec);
const lastCheckTime = {
    encoding: 'utf-8',
    file: path_1.default.join(__dirname, 'zanproxy.last-check.tmp'),
    get: () => {
        const { file, encoding } = lastCheckTime;
        if (!fs_1.default.existsSync(file)) {
            return null;
        }
        const content = fs_1.default.readFileSync(file, { encoding });
        if (!content.length) {
            return null;
        }
        try {
            return parseInt(content, 10);
        }
        catch (error) {
            return null;
        }
    },
    set: () => {
        const { file, encoding } = lastCheckTime;
        fs_1.default.writeFileSync(file, Date.now(), { encoding });
        return;
    },
};
exports.default = () => __awaiter(this, void 0, void 0, function* () {
    const lastTime = lastCheckTime.get();
    const hasCheckedRecently = lastTime && Date.now() - lastTime < 24 * 3600 * 1000;
    if (hasCheckedRecently) {
        return;
    }
    lastCheckTime.set();
    const checkSpinner = ora_1.default('正在检查更新...').start();
    const isLatest = yield isUpdated(packageInfo);
    checkSpinner.stop();
    if (isLatest) {
        console.log('当前已是最新版本');
        return;
    }
    const ans = yield inquirer_1.prompt([
        {
            message: '检测到新版本，是否更新？',
            name: 'shouldUpdate',
            type: 'confirm',
        },
    ]);
    if (!ans.shouldUpdate) {
        return;
    }
    const updateSpinner = ora_1.default('正在更新').start();
    return update(packageInfo)
        .catch(() => exec(`npm uninstall --global --silent ${packageInfo.name}`))
        .then(() => exec(`npm install --global --silent ${packageInfo.name}`))
        .then(() => {
        updateSpinner.stop();
        console.log(`更新完成，请重新启动! 如出现命令丢失情况，请手动重新安装：npm install -g ${packageInfo.name}`);
        process.exit(0);
    })
        .catch(error => {
        console.error('更新失败', error);
        process.exit(1);
    });
});
//# sourceMappingURL=selfUpdate.js.map