import * as crc from 'crc';

interface ServerInfo {
    id: string;
    serverType: string;
    host: string;
    port: number;
    clientHost?: string;
    clientPort?: number;
    frontend ?: boolean;

    args ?: string | string[];
    cpu ?: number;

}




let roleRoute = new Map<string, Map<string, string>>()

export function dispatch(uid: string, connectors: ServerInfo[], serverType: string = '') {
    //测试代码
    // if (serverType == 'activity') {
    //     if (uid == 'SPDtGqx9Gw') {
    //         if (connectors.length > 1) {
    //             connectors = connectors.filter(obj => { return obj.id != 'activity-server-1' })
    //         }
    //     } else {
    //         connectors = connectors.filter(obj => { return obj.id == 'activity-server-1' })
    //     }
    // }

    if (serverType) {
        let roleRouteData = roleRoute.get(uid);
        let serverId = '';
        if (roleRouteData) {
            serverId = roleRouteData.get(serverType);
            if (serverId) {
                let index = connectors.findIndex(obj => { return obj.id === serverId });
                if (index != -1) {
                    // console.log('aaaaaaaaa 1', roleRouteData)
                    return connectors[index];
                }
            }
        }
        let index = Math.abs(crc.crc32(uid)) % connectors.length;
        if (!roleRouteData) {
            roleRouteData = new Map<string, string>()
        }
        roleRouteData.set(serverType, connectors[index].id);
        roleRoute.set(uid, roleRouteData)
        // console.log('aaaaaaaaa 2', roleRouteData)
        return connectors[index];
    }
    let index = Math.abs(crc.crc32(uid)) % connectors.length;
    return connectors[index];
}