"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 koa_router_1 = __importDefault(require("koa-router"));
const typedi_1 = require("typedi");
const services_1 = require("../../services");
/**
 * Created by tsxuehu on 4/11/17.
 */
let RuleController = class RuleController {
    regist(router) {
        // 创建规则
        // {
        //    name:name,
        //    description:description
        // }
        const ruleRouter = new koa_router_1.default({
            prefix: '/rule',
        });
        ruleRouter.post('/create', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const userId = ctx.userId;
            try {
                const result = yield this.ruleService.createRuleFile(userId, ctx.request.body.name, ctx.request.body.description);
                ctx.body = {
                    code: 0,
                    msg: result,
                };
                return;
            }
            catch (error) {
                const msg = error === services_1.ErrNameExists
                    ? '文件已存在'
                    : `未知错误: ${error.toString()}`;
                ctx.body = {
                    code: 1,
                    msg,
                };
            }
        }));
        // 获取规则文件列表
        // /rule/filelist
        ruleRouter.get('/filelist', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const userId = ctx.userId;
            const ruleFileList = yield this.ruleService.getRuleFileList(userId);
            ctx.body = {
                code: 0,
                list: ruleFileList,
            };
        }));
        // 删除规则文件
        // /rule/deletefile?name=${name}
        ruleRouter.get('/deletefile', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const userId = ctx.userId;
            yield this.ruleService.deleteRuleFile(userId, ctx.query.name);
            ctx.body = {
                code: 0,
            };
        }));
        // 设置文件勾选状态
        // /rule/setfilecheckstatus?name=${name}&checked=${checked?1:0}
        ruleRouter.get('/setfilecheckstatus', ctx => {
            const userId = ctx.userId;
            this.ruleService.setRuleFileCheckStatus(userId, ctx.query.name, parseInt(ctx.query.checked, 10) === 1 ? true : false);
            ctx.body = {
                code: 0,
            };
        });
        // 设置文件勾选状态
        // /rule/setfiledisablesync?name=${name}&diable=${disable?1:0}
        ruleRouter.get('/setfiledisablesync', ctx => {
            const userId = ctx.userId;
            this.ruleService.setRuleFileDisableSync(userId, ctx.query.name, parseInt(ctx.query.disable, 10) === 1 ? true : false);
            ctx.body = {
                code: 0,
            };
        });
        // 获取规则文件
        // /rule/getfile?name=${name}
        ruleRouter.get('/getfile', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const userId = ctx.userId;
            const content = yield this.ruleService.getRuleFile(userId, ctx.query.name);
            ctx.body = {
                code: 0,
                data: content,
            };
        }));
        // 保存规则文件
        // /rule/savefile?name=${name} ,content
        ruleRouter.post('/savefile', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const userId = ctx.userId;
            yield this.ruleService.saveRuleFile(userId, ctx.request.body);
            ctx.body = {
                code: 0,
            };
        }));
        // 重命名规则文件
        // /rule/changefilename/:origin, body -> { name, description }
        ruleRouter.post('/updatefileinfo/:origin', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const { userId, params, request } = ctx;
            const { origin } = params;
            const { name, description } = request.body;
            try {
                yield this.ruleService.updateFileInfo(userId, origin, {
                    description,
                    name,
                });
                ctx.body = {
                    code: 0,
                };
            }
            catch (e) {
                const msg = e === services_1.ErrNameExists ? '有重复名字' : `未知错误: ${e.toString()}`;
                ctx.body = {
                    code: 1,
                    msg,
                };
            }
        }));
        // 导出规则文件
        // /rule/download?name=${name}
        ruleRouter.get('/download', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const userId = ctx.userId;
            const name = ctx.query.name;
            const content = yield this.ruleService.getRuleFile(userId, name);
            ctx.set('Content-disposition', `attachment;filename=${encodeURI(name)}.json`);
            ctx.body = content;
        }));
        // 测试规则
        // /rule/test
        ruleRouter.post('/test', (ctx) => __awaiter(this, void 0, void 0, function* () {
            /*
                   url: '',// 请求url
                   match: '',// url匹配规则
                   targetTpl: '',// 路径模板， 会用urlReg的匹配结果来替换targetTpl $1 $2
                   matchRlt: '',// url匹配结果
                   targetRlt: ''// 路径匹配结果
                   */
            const userId = ctx.userId;
            const match = ctx.request.body.match;
            const url = ctx.request.body.url;
            let matchRlt = '不匹配';
            if (match && (url.indexOf(match) >= 0 || new RegExp(match).test(url))) {
                matchRlt = 'url匹配通过';
            }
            const targetTpl = ctx.request.body.targetTpl;
            const targetRlt = yield this.profileService.calcPath(userId, url, match, targetTpl);
            // 测试规则
            ctx.body = {
                code: 0,
                data: {
                    matchRlt,
                    targetRlt,
                },
            };
        }));
        ruleRouter.get('/import', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const { userId, query } = ctx;
            const ruleFileUrl = query.url;
            try {
                const ruleFile = yield this.ruleService.importRemoteRuleFile(userId, ruleFileUrl);
                ctx.body = {
                    code: 0,
                    data: ruleFile,
                };
            }
            catch (e) {
                ctx.body = {
                    code: 1,
                    msg: e,
                };
            }
        }));
        ruleRouter.get('/copy', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const userId = ctx.userId;
            const name = ctx.query.name;
            const copied = yield this.ruleService.copyRuleFile(userId, name);
            ctx.body = {
                code: 0,
                data: copied,
            };
        }));
        router.use(ruleRouter.routes(), ruleRouter.allowedMethods());
    }
};
__decorate([
    typedi_1.Inject(),
    __metadata("design:type", services_1.RuleService)
], RuleController.prototype, "ruleService", void 0);
__decorate([
    typedi_1.Inject(),
    __metadata("design:type", services_1.ProfileService)
], RuleController.prototype, "profileService", void 0);
RuleController = __decorate([
    typedi_1.Service()
], RuleController);
exports.RuleController = RuleController;
//# sourceMappingURL=rule.js.map