import { GroupMessageType } from './../../../db/GroupMessage';
import { Application, ChannelService } from 'pinus';
import { resResult } from '../../../pubUtils/util';
import { ON_ADD_CHANNEL_ROUTE, ON_GROUP_MSG_ROUTE, ON_LEAVE_CHANNEL_ROUTE, STATUS, CHANNEL_PREFIX } from '../../../consts';
import { PrivateMessageType } from '../../../db/PrivateMessage';
import { addUserToChannel, getSimpleRoleInfo } from '../../../services/roleService';
import { ChannelUser } from '../../../domain/ChannelUser';
import { getWorldChannelSid, groupRoomId } from '../../../services/chatService';
import { reloadResources } from '../../../pubUtils/data';
import { GeneralRankParamRole, GeneralRankParamBattle } from '../../../domain/rank';
import { getAllGuildActivityStatus } from '../../../services/guildActivityService';
import { MailParam } from '../../../domain/roleField/mail';

export default function (app: Application) {
    return new ChatRemote(app);
}

// rpc 定义挪到单独的定义文件(user.rpc.define.ts)。解决ts-node 有可能找不到定义的问题。
// 你也可以用其它方法解决，或者没有遇到过这个问题的话，定义还是可以放在这里。

// UserRpc的命名空间自动合并
// declare global {
//     interface UserRpc {
//         chat: {
//             chatRemote: RemoterClass<FrontendSession, ChatRemote>;
//         };
//     }
// }
export class ChatRemote {

    constructor(private app: Application) {
        this.app = app;
        this.channelService = app.get('channelService');
    }

    private channelService: ChannelService;
    private GUILD_ACTIVITY_END = 'onGuildActivityEnd';
    private RACE_ACTIVITY_START = 'onRaceStart';
    private RANK_TOP_UPDATE = 'onRankTopUpdated';
    private GUILD_ACTIVITY_STATUS_UPDATE = 'onGuildActivityStatus'; // 军团活动状态变化

    /**
     * 加入世界频道（分服）.
     *
     * @param {String} roleId roleId
     * @param {String} sid server id
     * @param {String} serverId 区id
     * @param {boolean} flag 是否创建新channel
     *
     */
    public async addWorldChannel(roleId: string, serverId: number, sid: string, flag: boolean = true) {
        const name = `world${serverId}`;
        let channel = this.channelService.getChannel(name, flag);
        if (!channel) return;
        channel.add(roleId, sid);
        let param = {
            roleId
        };
        channel.pushMessage('onWorldAdd', resResult(STATUS.SUCCESS, param));

        return this.getWorldChannel(name);
    }

    /**
     * Get user from chat channel.
     *
     * @param {Object} opts parameters for request
     * @param {String} name channel name
     * @param {boolean} flag channel parameter
     * @return {Array} users uids in channel
     *
     */
    private getWorldChannel(name: string, flag: boolean = true): Array<any> {
        let users: string[] = [];
        let channel = this.channelService.getChannel(name, flag);
        if (!!channel) {
            users = channel.getMembers();
        }
        for (let i = 0; i < users.length; i++) {
            users[i] = users[i].split('*')[0];
        }
        return users;
    }

    /**
     * 踢出世界频道.
     *
     * @param {String} roleId roleId
     * @param {String} sid server id
     * @param {String} serverId 区id
     *
     */
    public async kickWorldChannel(roleId: string, sid: string, serverId: number) {
        const name = `world${serverId}`;

        let channel = this.channelService.getChannel(name, false);
        // leave channel
        if (!channel) return;
        channel.leave(roleId, sid);
        let param = {
            roleId
        };
        channel.pushMessage('onLeave', resResult(STATUS.SUCCESS, param));
    }

    /**
     * 向世界频道全服发送消息
     * 
     * @param serverId 区id
     * @param param 信息
     */
    public async sendWorldMessage(serverId: number, param: any) {
        const name = `world${serverId}`;

        let channel = this.channelService.getChannel(name, false);
        // leave channel
        if (!!channel) {
            channel.pushMessage('onWorldMessage', resResult(STATUS.SUCCESS, param));   
        }
    }

    /**
     * @description 添加用户到频道
     * @param {string} channelName 频道名
     * @param {string} roleId 要添加的用户名
     * @param {string} sid 用户连接的前端服务器名
     * @memberof ChatRemote
     */
    public async addChannel(channelName: string, roleId: string, sid: string) {
        let channel = this.channelService.getChannel(channelName, true);
        if (!channel) return;
        addUserToChannel(channel, new ChannelUser(roleId, sid));
        channel.pushMessage(ON_ADD_CHANNEL_ROUTE, resResult(STATUS.SUCCESS, { roleId, channelName }));
    }

    /**
     * @description 从频道中删除用户
     * @param {string} channelName
     * @param {string} roleId
     * @param {string} sid
     * @memberof ChatRemote
     */
    public async leaveChannel(channelName: string, roleId: string, sid: string) {
        let channel = this.channelService.getChannel(channelName, false);
        // leave channel
        if (!channel) return;
        channel.leave(roleId, sid);
        let param = {
            roleId,
            channelName
        };
        channel.pushMessage(ON_LEAVE_CHANNEL_ROUTE, resResult(STATUS.SUCCESS, param));
    }

    /**
     * @description 推送群消息到频道
     * @param {Partial<GroupMessageType>} msg
     * @memberof ChatRemote
     */
    public async sendGroupMsg(roomId: string, msg: Partial<GroupMessageType>) {
        let channel = this.channelService.getChannel(roomId, false);
        if (!channel) return;
        const roleInfo = await getSimpleRoleInfo(msg.roleId);
        channel.pushMessage(ON_GROUP_MSG_ROUTE, resResult(STATUS.SUCCESS, { ...msg, roleInfo }));
    }

    /**
     * @description 推送私聊消息
     * @param {Partial<PrivateMessageType>} msg
     * @memberof ChatRemote
     */
    public async sendPrivateMsg(msg: Partial<PrivateMessageType>) {

    }

    /**
     * @description 全服推送活动结束通知
     * @param serverId 
     */
    public async sendGuildActivityEnd(serverId: number) {
        let roomId = groupRoomId(CHANNEL_PREFIX.WORLD, serverId);
        let channel = this.channelService.getChannel(roomId, false);
        if (!channel) return;
        channel.pushMessage(this.GUILD_ACTIVITY_END, resResult(STATUS.SUCCESS, { }));
    }

    /**
     * @description 全服推送竞赛活动开始通知
     * @param serverId 
     */
    public async sendRaceActivityStart(serverId: number) {
        let roomId = groupRoomId(CHANNEL_PREFIX.WORLD, serverId);
        let channel = this.channelService.getChannel(roomId, false);
        if (!channel) return;
        channel.pushMessage(this.RACE_ACTIVITY_START, resResult(STATUS.SUCCESS, { }));
    }

    /**
     * @description 全服推送排行榜更新信息
     * @param serverId 
     */
    public async sendRankTopUpdated(serverId: number, rank: (GeneralRankParamRole|GeneralRankParamBattle)&{general: number}) {
        
        let roomId = groupRoomId(CHANNEL_PREFIX.WORLD, serverId);
        let channel = this.channelService.getChannel(roomId, false);
        if (!channel) return;
        channel.pushMessage(this.RANK_TOP_UPDATE, resResult(STATUS.SUCCESS, { rank }));
    }

    /**
     * 重载json资源
     */
    public async reloadResources() {
        reloadResources();
    }


    /**
     * @description 全服推送军团活动状态变化
     * @param serverId 
     */
    public async sendGuildActivityUpdate(serverId: number) {
        let roomId = groupRoomId(CHANNEL_PREFIX.WORLD, serverId);
        let channel = this.channelService.getChannel(roomId, false);
        if (!channel) return;
        let guildActivities = getAllGuildActivityStatus();
        channel.pushMessage(this.GUILD_ACTIVITY_STATUS_UPDATE, resResult(STATUS.SUCCESS, { guildActivities }));
    }

    /**
     * 向全服推送邮件
     * @param serverId 服务器id 
     * @param path 推送地址
     * @param mails 邮件内容
     */
    public async sendMail(serverId: number, path: string, data: { mails: MailParam[] }) {
        let roomId = groupRoomId(CHANNEL_PREFIX.WORLD, serverId);
        let channel = this.channelService.getChannel(roomId, false);
        if (!channel) return;
        channel.pushMessage(path, resResult(STATUS.SUCCESS, data));
    }
}
