package com.ch.jedge.jbot.intent.bot;

import com.ch.jedge.jbot.intent.JedgeJBotCBService;
import com.ch.jedge.utils.JEVdbConfigUtil;
import com.changhong.jedge.JESocketClient;
import com.changhong.qlib.QData;
import com.changhong.qlib.intf.QIData;
import com.changhong.qlib.util.cmdline.ArgUtils;
import com.changhong.qlib.util.cmdline.CmdUtils;
import com.changhong.qlib.util.sync.SystemUtils;

public class JBotAppBase  extends QData implements CmdUtils.CmdController {

    public JBotAppBase(String botName) {
        setName(botName);
    }

    @Override
    public String getControllerName() {
        return getName();
    }

    @Override
    public void setControllerName(String s) {
        setName(s);
    }


    public static void run(String appName, Class<? extends JedgeJBotCBService> serviceCls , String[] args) {

        final JBotAppBase instance =
                new JBotAppBase(appName);

        JEVdbConfigUtil.loadConfigs();

        JBotAppClient jsBot = JBotAppClient.getInstance(appName, serviceCls);
        if(jsBot==null) {
            JESocketClient.markLogSt("应用 [%s] 创建服务 (%s) 失败,退出!",appName, serviceCls.getSimpleName());
            JEVdbConfigUtil.releaseConfigs();
            return;
        }
        QIData param = ArgUtils.handleArgVList(args);

        boolean runBack = JEVdbConfigUtil.setupInitConfigs(jsBot, param, appName);

        if(!jsBot.start()) {
            jsBot.errLog("Fail to start ap app : " + jsBot.getName());
            return;
        }

        while(!jsBot.isActive()) {
            //等待接入成功
            jsBot.warnLog("Wait for apApp to connect to mgbus : " + jsBot.getName());
            SystemUtils.tryWait(2000);
        }

        CmdUtils.run(instance, runBack, param);

        jsBot.shutdown();

        JEVdbConfigUtil.releaseConfigs();
    }

}
