import { Container } from "typescript-ioc";
import { IService, IWsService } from "mslib";
import { IServiceProxy } from "proxy/IServiceProxy";
import { ServiceProxy } from "proxy/ServiceProxy";

//下面這個requires是个占位符，不可删除

// 自动注册的服务列表（由构建工具或启动时填充）
const autoRegisteredServices: Array<{ sid: string; service: IService }> = [];

/**
 * 注册服务到路由表
 */
export function registerService(sid: string, service: IService, contentType: string = 'application/json') {
    autoRegisteredServices.push({ sid: sid.toLowerCase(), service });
}

export class ServiceRouters {

    private routers = new Map<String, IServiceProxy>();
    private wsRouters = new Map<String, IWsService>();

    constructor() {
        this.initRouters();
    }

    private initRouters() {
        autoRegisteredServices.forEach(item => {
            this.routers.set(item.sid, new ServiceProxy(item.sid, 'application/json', item.service));
        });
    }

    refreshRouters() {
        this.routers.clear();
        this.initRouters();
    }

    match(sid: string): IServiceProxy {
        return this.routers.get((sid || '').toLowerCase());
    }

    matchWS(sid: string): IWsService {
        return this.wsRouters.get((sid || '').toLowerCase());
    }
}
