package com.eactive.eai.rms.onl.common.service;

import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.onl.apim.portalstatistics.PortalStatisticsManService;
import com.eactive.eai.rms.onl.apim.portalstatistics.PortalStatisticsUI;
import com.eactive.eai.rms.onl.common.util.DateUtil;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class PortalStatisticsDailyJob implements Job {
    /**
    * Logger for this class
    */
    private static final Logger logger = Logger.getLogger(PortalStatisticsDailyJob.class);

    /** The monitoring context. */
    private transient MonitoringContext monitoringContext;

    @Override
	public void execute(JobExecutionContext context) throws JobExecutionException {

        if (logger.isInfoEnabled()) {
            logger.info("*** START PortalStatisticsDailyJob run("
                    + CommonUtil.getToday("yyyy-MM-dd HH:mm") + ")");
        }

		ApplicationContext appContext = null;
		try {
			appContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
		} catch (SchedulerException e) {
			logger.error("applicationContext get module error",e);
			return ;
		}  
		monitoringContext    = (MonitoringContext)appContext.getBean("monitoringContext");

        PortalStatisticsManService portalStaticsManService = appContext.getBean(PortalStatisticsManService.class);

        PortalStatisticsUI portalStatisticsUI = new PortalStatisticsUI();

        // 현재 날짜와 시간 가져오기
        LocalDateTime now = LocalDateTime.now();

        // 10분 전의 시간 계산
        LocalDateTime tenMinutesAgo = now.minusMinutes(10);

        // 원하는 형식의 DateTimeFormatter 생성
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");

        // 10분 전 시간을 원하는 형식의 문자열로 변환
        String formattedDateTime = tenMinutesAgo.format(formatter);

        portalStatisticsUI.setStartDate(formattedDateTime);
        portalStaticsManService.createTenMinuteData(portalStatisticsUI);

        if (logger.isInfoEnabled()) {
            logger.info("*** END PortalStatisticsDailyJob run("
                    + DateUtil.getDateTime("yyyy-MM-dd HH:mm") + ")");
        }
	}    


}
