package com.utic.center.utic.stat.server.service;

import com.utic.center.common.dto.ProcessStateDto;
import com.utic.center.utic.stat.server.config.ApplicationConfig;
import com.utic.center.utic.stat.server.dao.repository.ProcessRepository;
import com.utic.center.utic.stat.server.repository.ApplicationRepository;
import lombok.Getter;
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;

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

    private final ProcessRepository repo;
    private final ApplicationConfig config;

    @PostConstruct
    private void init() {
        log.info("ProcessStateService.init: start.");
        log.info("ProcessStateService.init. processId: {}.", this.config.getProcessId());
        log.info("ProcessStateService.init: ..end.");
    }

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

    public void processStop() {
        ApplicationRepository.processState.setRunState(ProcessStateDto.RUN_STATE.STOP.getValue());
        updateProcessState(false);
    }

    public void processStart() {
        ApplicationRepository.processState.setRunState(ProcessStateDto.RUN_STATE.NORMAL.getValue());
        updateProcessState(true);
    }

    public void processRunning() {
        processStart();
    }
    private void updateProcessState(boolean isRun) {
        this.repo.updateProcessState(ApplicationRepository.processState);
    }
}
