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

import cn.reghao.bnt.common.agent.app.iface.AppDeploy;
import cn.reghao.bnt.common.machine.Machine;
import cn.reghao.bnt.common.msg.MessageSender;
import cn.reghao.bnt.common.msg.event.EvtAppDeploy;
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:52:04
 */
public class EvtAppDeployHandler extends Handler {
    private final MessageSender messageSender;
    private final AppDeploy appDeploy;

    public EvtAppDeployHandler(MessageSender messageSender, AppDeploy appDeploy) {
        this.messageSender = messageSender;
        this.appDeploy = appDeploy;
    }

    @Override
    public void handle(Event evt) {
        EvtAppDeploy deployParam = (EvtAppDeploy) evt;
        String appId = deployParam.getAppId();
        EvtAppStatResult statResult;
        try {
            statResult = appDeploy.deploy(deployParam);
            statResult.setResult(Result.result(ResultStatus.SUCCESS));
        } catch (Exception e) {
            statResult = new EvtAppStatResult(appId, Machine.ID);
            statResult.setResult(Result.result(ResultStatus.FAIL, ExceptionUtil.errorMsg(e)));
        }

        statResult.setDeploy(true);
        EventMessage evtMsg = EventMessage.evt(statResult);
        try {
            messageSender.send("", evtMsg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
