import {Application, RouteRecord, FrontendOrBackendSession, HandlerCallback } from "pinus";
import { GM_API_TYPE, STATUS } from "../../../consts";
import { GMGroupModel } from "../../../db/GMGroup";
import { GMRecordModel } from "../../../db/GMRecord";
import { gameData } from "../../../pubUtils/data";
import { resResult } from "../../../pubUtils/util";

export function tokenFilter(app: Application) {
    return new Filter(app);
}

var Filter = function(this: any, app: Application) {
    this.app = app;
};

Filter.prototype.before = async function (routeRecord: RouteRecord, msg: any, session: FrontendOrBackendSession, next: HandlerCallback) {
    const uid = session.get('uid');
    const groupId = session.get('groupId');

    let route = routeRecord.route;
    // console.log('********uid', uid, route);
    let dicApi = gameData.apiByUrl.get(route);
    if(!dicApi) {
        return next(new Error(), resResult(STATUS.GM_MISS_API));
    }
    let group = await GMGroupModel.getGroupById(groupId);
    
    if(!group) {
        return next(new Error(), resResult(STATUS.GM_NO_AUTHORITY_GET));
    } 

    if(!group.apis.includes(0) && !group.apis.includes(dicApi.id)) {
        return next(new Error(), resResult(STATUS.GM_NO_AUTHORITY_GET));
    }

    next(null);
};

Filter.prototype.after = function (err: Error, routeRecord: RouteRecord, msg: any, session: FrontendOrBackendSession, resp: any, next: HandlerCallback) {
    const uid = session.get('uid');
    let route = routeRecord.route;
    
    let dicApi = gameData.apiByUrl.get(route);
    if(dicApi && dicApi.type != GM_API_TYPE.find) {
        GMRecordModel.createRecord(uid, this.app.get('env'), route, JSON.stringify(msg||{}), JSON.stringify(resp||{}));
    }
    next(err);
};