import {Application, RouteRecord, FrontendOrBackendSession, HandlerCallback, pinus} from "pinus";
// import { checkEvent } from '../../../services/eventSercive';
import { refresh } from '../../../services/refreshService';
import { checkFilterWords, getWorldChannelSid } from "../../../services/chatService";
import { resResult, checkWhiteListWithUid } from "../../../pubUtils/util";
import { STATUS } from "../../../consts";
import { UserModel } from "../../../db/User";
export function globalFilter(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 serverId: number = session.get('serverId');
    const sid: string = session.get('sid');
    const roleId: string = session.get('roleId');
    const uid: number = session.get('userid');
    
    session.push('teamCode', () => {});

    const maintenServers = this.app.get('maintenServers');
    if(maintenServers && maintenServers.indexOf(serverId) != -1) { // 该服务器维护
        let isWhiteList = await checkWhiteListWithUid(uid);
        if(isWhiteList) return next(null);

        pinus.app.get('channelService').pushMessageByUids('onServerMaintenance', resResult(STATUS.SERVER_MAINTENANCE), [{ uid: roleId, sid }]);
        return next(new Error(), resResult(STATUS.SERVER_MAINTENANCE));
    }

    let hasBlockWords = false;
    if(pinus.app.get('env') == 'production') {
        if(routeRecord.route == 'guild.guildHandler.createGuild') {
            hasBlockWords = await checkFilterWords(msg.name);
        } else if (routeRecord.route == 'role.roleHandler.initRole') {
            hasBlockWords = await checkFilterWords(msg.roleName);
        } else if (routeRecord.route == 'role.roleHandler.rename') {
            hasBlockWords = await checkFilterWords(msg.roleName);
        }
    }
    if(hasBlockWords) return next(new Error(), resResult(STATUS.BLOCK_WORDS));

    next(null);
};

Filter.prototype.after = async function (err: Error, routeRecord: RouteRecord, msg: any, session: FrontendOrBackendSession, resp: any, next: HandlerCallback) {
    //刷新
    await refresh(session);
    // return checkEvent(session).then(()=>{
    //     next(err);
    // }).catch(e => {
    //     console.error(e);
    //     next(err);
    // });    // 奇遇本检查
    next(null);
};