import { STATUS } from './../../../consts/statusCode';
import { dispatch } from '../../../pubUtils/dispatcher';
import { Application, BackendSession, HandlerService, pinus, } from 'pinus';
import { resResult } from '../../../pubUtils/util';

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

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

    /**
     * Gate handler that dispatch user to connectors.
     *
     * @param {Object} msg message from client
     * @param {Object} session
     *
     */
    async queryEntry(msg: { userCode: string }, session: BackendSession) {
        let { userCode } = msg;
        if (!userCode) {
            return resResult(STATUS.WRONG_PARMS);
        }
        // get all connectors
        let connectors = this.app.getServersByType('connector');
        // console.log(connectors);
        if (!connectors || connectors.length === 0) {
            return resResult(STATUS.CONNECTOR_ERR);
        }
        // select connector
        let res = dispatch(userCode, connectors, 'connector');
        return resResult(STATUS.SUCCESS, { host: res.clientHost, port: res.clientPort });
    }
}