import { Application, BackendSession, HandlerService, pinus, } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { ENCRYPT_IV, ENCRYPT_KEY, STATUS, TASK_TYPE } from '../../../consts';
import { ActivityGroupModel } from '../../../db/ActivityGroup';
import { getActivitiesWithOrder, getActivity, getActivityById, getActivityByServerId, shouldReplace } from '../../../services/activity/activityService';
import { ActivityModelType } from '../../../db/Activity';
import { UserOrderModel } from '../../../db/UserOrder';

export default function (app: Application) {
    new HandlerService(app, {});
    return new ActivityHandler(app);
}

export class ActivityHandler {
    constructor(private app: Application) {
    }


    /**
    * @description 活动是否开启总接口
    * @param {{ }} msg
    * @param {BackendSession} session
    * @memberof ActivityHandler
    */
    async getAllOpenActivity(msg: {}, session: BackendSession) {

        const { } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const guildCode = session.get('guildCode');
        const uid: number = session.get('userid');
        const sid: string = session.get('sid');
        
        let originActivities = await getActivityByServerId(serverId);
        let maxIdByType = new Map<number, number>(); // type => max
        let activityById = new Map<number, any>(); // id => activity

        for(let activity of originActivities) {
            let playerActivityData = await getActivity(serverId, roleId, uid, guildCode, activity.activityId, activity.type);
            if(!playerActivityData) continue;

            let shouldPush = true;
            if(shouldReplace(playerActivityData.type)) { // 该类型只能有一个id，选最大的那个
                let max = maxIdByType.get(playerActivityData.type)||0;
                if(playerActivityData.activityId > max) {
                    activityById.delete(max);
                    maxIdByType.set(playerActivityData.type, playerActivityData.activityId);
                } else {
                    shouldPush = false;
                }
            }
            if(shouldPush) activityById.set(activity.activityId, playerActivityData);
        }

        let groups = await ActivityGroupModel.findByServerId(serverId);
        let playerGroupArray = [];
        for (let groupData of groups) {
            let playerGroupActivityArray = [];
            for (let activityId of groupData.activities) {
                let playerActivityData = activityById.get(activityId);
                if(playerActivityData) {
                    playerGroupActivityArray.push(playerActivityData);
                }
            }
            playerGroupArray.push({
                id: groupData.groupId,
                type: groupData.type,
                activities: playerGroupActivityArray
            });
            console.log(`${roleId} 活动合集  groupId:${groupData.groupId}, 合集类型${groupData.type}, 一共${playerGroupActivityArray.length}个`)
        }

        return resResult(STATUS.SUCCESS, { playerActivityArray: [], playerGroupArray });
    }

    async getActivitiesByOrder(msg: { localOrderID: string }, session: BackendSession) {
        
        const { localOrderID } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const guildCode = session.get('guildCode');
        const uid = session.get('userid');

        let orderInfo = await UserOrderModel.findOrder(localOrderID);
        if (!orderInfo || orderInfo.roleId != roleId) {
            return resResult(STATUS.NO_ORDER);
        }
        let activities: ActivityModelType[] = await getActivitiesWithOrder(orderInfo);
        let result = [];
        for(let activityData of activities) {
            if (!activityData) continue;

            let playerActivityData = await getActivity(serverId, roleId, uid, guildCode, activityData.activityId, activityData.type);
            if(playerActivityData) {
                result.push(playerActivityData);
            }
        }
        return resResult(STATUS.SUCCESS, { activities: result });
    }

    async debugActivityMemory(msg: {}, session: BackendSession) {
        const {  } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid: string = session.get('sid');
        
        let activities = pinus.app.get('activities');
        let activityByType = pinus.app.get('activityByType');
        let activityByServer = pinus.app.get('activityByServer');
        let groupToServer = pinus.app.get('groupToServer');
        console.log('****** activities', activities);
        console.log('****** activityByType', activityByType);
        console.log('****** activityByServer', activityByServer);
        console.log('****** groupToServer', groupToServer);
        return resResult(STATUS.SUCCESS, { activities: [...activities], activityByType: [...activityByType], activityByServer: [...activityByServer], groupToServer: [...groupToServer] });
    }
}
