package cn.reghao.bnt.agent.ws.event.handler;

import cn.reghao.bnt.common.agent.app.iface.AppStat;
import cn.reghao.bnt.common.machine.Machine;
import cn.reghao.bnt.common.msg.MessageSender;
import cn.reghao.bnt.common.msg.constant.AppStatOps;
import cn.reghao.bnt.common.msg.event.EvtAppStat;
import cn.reghao.bnt.common.msg.event.EvtAppStatResult;
import cn.reghao.jutil.jdk.event.handler.Handler;
import cn.reghao.jutil.jdk.event.message.Event;
import cn.reghao.jutil.jdk.event.message.EventMessage;
import cn.reghao.jutil.jdk.exception.ExceptionUtil;
import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.jutil.jdk.web.result.ResultStatus;

import java.io.IOException;

/**
 * @author reghao
 * @date 2023-03-01 10:21:40
 */
public class EvtAppStatHandler extends Handler {
    private final MessageSender messageSender;
    private final AppStat appStat;

    public EvtAppStatHandler(MessageSender messageSender, AppStat appStat) {
        this.messageSender = messageSender;
        this.appStat = appStat;
    }

    @Override
    public void handle(Event evt) {
        EvtAppStat evtAppStat = (EvtAppStat) evt;
        String appId = evtAppStat.getAppId();
        String ops = evtAppStat.getOps();

        EvtAppStatResult statResult;
        try {
            switch (AppStatOps.valueOf(ops)) {
                case start:
                    statResult = appStat.start(evtAppStat);
                    statResult.setResult(Result.result(ResultStatus.SUCCESS));
                    break;
                case stop:
                    statResult = appStat.stop(evtAppStat);
                    statResult.setResult(Result.result(ResultStatus.SUCCESS));
                    break;
                case restart:
                    statResult = appStat.restart(evtAppStat);
                    statResult.setResult(Result.result(ResultStatus.SUCCESS));
                    break;
                case stat:
                    statResult = appStat.stat(evtAppStat);
                    statResult.setResult(Result.result(ResultStatus.SUCCESS));
                    break;
                default:
                    statResult = new EvtAppStatResult(appId, Machine.ID);
                    String msg = String.format("应用状态操作类型 %s 不存在", ops);
                    statResult.setResult(Result.result(ResultStatus.ERROR, msg));
            }
        } catch (Exception e) {
            statResult = new EvtAppStatResult(appId, Machine.ID);
            statResult.setResult(Result.result(ResultStatus.FAIL, ExceptionUtil.errorMsg(e)));
        }

        EventMessage evtMsg = EventMessage.evt(statResult);
        try {
            messageSender.send(Machine.ID, evtMsg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
