"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
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 es6_promisify_1 = require("es6-promisify");
const events_1 = __importDefault(require("events"));
const fs_1 = __importDefault(require("fs"));
const jsonfile_1 = __importDefault(require("jsonfile"));
const lodash_1 = require("lodash");
const path_1 = __importDefault(require("path"));
const typedi_1 = require("typedi");
const appInfo_1 = require("./appInfo");
const jsonfileWriteFile = es6_promisify_1.promisify(jsonfile_1.default.writeFile);
const defaultProfile = {
    // 是否启用host解析
    enableHost: true,
    // 是否启用转发规则
    enableRule: true,
    // 工程路径配置
    projectPath: {},
};
/**
 * 代理运转需要的规则数据
 * 代理端口、超时时间、gitlab token、工程路径、是否启用转发规则
 * Created by tsxuehu on 8/3/17.
 */
let ProfileService = class ProfileService extends events_1.default {
    constructor(appInfoService) {
        super();
        // userId -> profile
        this.userProfileMap = {};
        // clientIp -> userId
        this.clientIpUserMap = {};
        const proxyDataDir = appInfoService.getProxyDataDir();
        this.profileSaveDir = path_1.default.join(proxyDataDir, 'profile');
        this.clientIpUserMapSaveFile = path_1.default.join(proxyDataDir, 'clientIpUserMap.json');
        const profileMap = fs_1.default
            .readdirSync(this.profileSaveDir)
            .filter(name => name.endsWith('.json'))
            .reduce((prev, curr) => {
            prev[curr] = jsonfile_1.default.readFileSync(path_1.default.join(this.profileSaveDir, curr));
            return prev;
        }, {});
        lodash_1.forEach(profileMap, (profile, fileName) => {
            const userId = fileName.slice(0, -5);
            // 补全profile数据
            // this.userProfileMap[userId] = assign({}, defaultProfile, profile);;
            this.userProfileMap[userId] = profile;
        });
        // 加载ip-> userID映射
        this.clientIpUserMap = jsonfile_1.default.readFileSync(this.clientIpUserMapSaveFile);
    }
    getProfile(userId) {
        return this.userProfileMap[userId] || defaultProfile;
    }
    setProfile(userId, profile) {
        return __awaiter(this, void 0, void 0, function* () {
            this.userProfileMap[userId] = profile;
            const filePath = path_1.default.join(this.profileSaveDir, `${userId}.json`);
            // 将数据写入文件
            yield jsonfileWriteFile(filePath, profile, { encoding: 'utf-8' });
            // 发送通知
            this.emit('data-change-profile', userId, profile);
        });
    }
    /**
     * 替换redirect中的变量引用,
     * 如果引用的变量不存在，则不做替换
     * @param clientIp
     * @param href
     * @param match
     * @param target
     */
    calcPath(userId, href, match, target) {
        if (match) {
            const matchList = href.match(new RegExp(match));
            lodash_1.forEach(matchList, (value, index) => {
                if (index === 0) {
                    return;
                }
                const reg = new RegExp('\\$' + index, 'g');
                if (!value) {
                    value = '';
                }
                target = target.replace(reg, value);
            });
            const compiled = lodash_1.template(target);
            const projectPath = this.getProfile(userId).projectPath;
            // 解析应用的变量
            return compiled(projectPath);
        }
    }
    /**
     *
     * @param userId
     * @param enable
     */
    setEnableRule(userId, enable) {
        return __awaiter(this, void 0, void 0, function* () {
            const conf = this.getProfile(userId);
            conf.enableRule = enable;
            yield this.setProfile(userId, conf);
        });
    }
    setEnableHost(userId, enable) {
        return __awaiter(this, void 0, void 0, function* () {
            const conf = this.getProfile(userId);
            conf.enableHost = enable;
            yield this.setProfile(userId, conf);
        });
    }
    /**
     * 获取转发规则启用开关
     * @param clientIp
     */
    enableRule(userId) {
        return this.getProfile(userId).enableRule;
    }
    enableHost(userId) {
        return this.getProfile(userId).enableHost;
    }
    // 获取clientIp对应的user id
    getClientIpMappedUserId(clientIp) {
        return this.clientIpUserMap[clientIp] || 'root';
    }
    // 将ip绑定至用户
    bindClientIp(userId, clientIp) {
        return __awaiter(this, void 0, void 0, function* () {
            const originUserId = this.clientIpUserMap[clientIp];
            this.clientIpUserMap[clientIp] = userId;
            yield jsonfileWriteFile(this.clientIpUserMapSaveFile, this.clientIpUserMap, { encoding: 'utf-8' });
            const clientIpList = this.getClientIpsMappedToUserId(userId);
            this.emit('data-change-clientIpUserMap', userId, clientIpList);
            if (originUserId) {
                const originClientIpList = this.getClientIpsMappedToUserId(originUserId);
                this.emit('data-change-clientIpUserMap', originUserId, originClientIpList);
            }
        });
    }
    // 获取用户绑定的clientip
    getClientIpsMappedToUserId(userId) {
        const ips = [];
        lodash_1.forEach(this.clientIpUserMap, (mapedUserId, ip) => {
            if (mapedUserId === userId) {
                ips.push(ip);
            }
        });
        return ips;
    }
};
ProfileService = __decorate([
    typedi_1.Service(),
    __metadata("design:paramtypes", [appInfo_1.AppInfoService])
], ProfileService);
exports.ProfileService = ProfileService;
//# sourceMappingURL=profile.js.map