package com.its.vds.stat.server.service;

import com.its.vds.stat.server.config.ApplicationConfig;
import com.its.vds.stat.server.dao.repository.UnitSystRepository;
import com.its.vds.stat.server.dto.UnitSystSttsDto;
import com.its.vds.stat.server.utils.SysUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Calendar;

@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(rollbackFor = {Exception.class})
public class UnitSystService {

	private final ApplicationConfig config;
	private final UnitSystRepository repo;
	private final UnitSystSttsDto unitSystStts = new UnitSystSttsDto();
	private int historyMin = -1;

	@PostConstruct
	private void init() {
		this.unitSystStts.setSystId(this.config.getProcessId());
	}

	@PreDestroy
	public void destroyService() {
		log.error("UnitSystService.destroy. system terminated.......");
		processStop();
	}

	public void processStop() {
		updateProcessState(false);
	}

	public void processStart() {
		updateProcessState(true);
	}

	public void processRunning() {
		processStart();
	}

	private void updateProcessState(boolean isRun) {
		boolean insHs = false;
		Calendar cal = Calendar.getInstance();
		int min = cal.get(Calendar.MINUTE);
		if (min % 5 == 0 && this.historyMin != min) {
				this.historyMin = min;
				insHs = true;
		}

		this.unitSystStts.setSystSttsCd(isRun ? "SPS1" : "SPC3");
		this.unitSystStts.setUpdtDt(SysUtils.getSysTime());

        this.repo.updateUnitSystStts(this.unitSystStts);

		if (insHs) {
            this.repo.insertUnitSystSttsHs(this.unitSystStts);
		}
	}

}