package com.its.pis.xnettcp.vds.process;

import com.its.app.AppUtils;
import com.its.app.utils.SysUtils;
import com.its.pis.ui.MainUI;
import com.its.pis.domain.NET;
import com.its.pis.entity.TbVdsCtlr;
import com.its.pis.xnettcp.vds.protocol.VdsResFramePacket;
import com.its.pis.xnetudp.service.CenterCommResponseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class Job_Temperature implements JobProtocol {

	private final VdsResFramePacket packet;

	@Override
	public int parse() {
		// 온도 & 전압 수신
		if (this.packet == null || this.packet.getVdsObj() == null) {
			log.error("Job_Temperature, packet or object data null");
			return 0;
		}

		TbVdsCtlr obj = this.packet.getVdsObj();
		byte[] body = this.packet.getBody();
		if (body == null || body.length != 3) {
			log.error("[{}]. Job_Temperature: Data Length Error, {}", obj.getVDS_CTLR_ID(), (body == null) ? 0 : body.length);
			return 0;
		}

		int CBOX_TMPR = body[0];
		int InputVoltage = (int)(body[1] & 0xFF);
		int OutputVoltage = (int)(body[2] & 0xFF);
		log.info("[{}]. Job_Temperature: Temperature {}, Input Voltage {}, Output Voltage {}", obj.getVDS_CTLR_ID(), CBOX_TMPR, InputVoltage, OutputVoltage);

		obj.getStts().setCBOX_TMPR(CBOX_TMPR);
		obj.getStts().setINPT_VOLT(InputVoltage);
		obj.getStts().setPRNT_VOLT(OutputVoltage);

		if (obj.getNetState() != NET.LOGINED) {
			String UPDT_DT = SysUtils.getSysTime();
			log.info("[{}]. Job_Temperature: First Received. Login Flag OK. {}", obj.getVDS_CTLR_ID(), UPDT_DT);
			obj.setNetState(NET.LOGINED);
			obj.getStts().setUPDT_DT(UPDT_DT);
			obj.getStts().setCMNC_STTS_CD("CMS0");

			// 클라이언트 연결 정보를 운영단말로 전송한다.
			CenterCommResponseService centerCommResponseService = (CenterCommResponseService) AppUtils.getBean(CenterCommResponseService.class);
			centerCommResponseService.notifyStatus(obj, true);
			MainUI mainUI = MainUI.getInstance();
			if (mainUI != null) {
				mainUI.updateCtlrStts(obj);
			}
		}

		return 1;
	}

}
