package com.caliverse.admin.logs.logservice.indicators;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.caliverse.admin.Indicators.Indicatordomain.IndicatorsLog;
import com.caliverse.admin.Indicators.indicatorrepository.IndicatorMcuRepository;
import com.caliverse.admin.logs.Indicatordomain.McuMongoLog;
import com.caliverse.admin.logs.logservice.businesslogservice.BusinessLogMcuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.caliverse.admin.Indicators.entity.McuLogInfo;

@Slf4j
@Service
public class IndicatorsMcuService {

    @Autowired private IndicatorMcuRepository mcuRepository;
    @Autowired private BusinessLogMcuService businessLogMcuService;
    
    public void collectMaxCountUser(String startTime, String endTime)
    {
        String logTimeStr = startTime.substring(0, 10);
        List<McuMongoLog> indicatorsLog = businessLogMcuService.loadBusinessLogData(startTime, endTime, McuMongoLog.class);

        if (indicatorsLog == null || indicatorsLog.isEmpty()) {
            McuLogInfo mcuLog = new McuLogInfo(logTimeStr, 0);
            log.info("collectMaxCountUser MCU Log Save logDay: {}, MaxCountUser: {}", logTimeStr, mcuLog.getMaxCountUser());
            saveStatLogData(mcuLog);
            return;
        }

        for(McuMongoLog mongo_log : indicatorsLog){
            String logDay = mongo_log.getLogDay();

            McuLogInfo mcuLog = new McuLogInfo(logDay, mongo_log.getMaxCountUser());
            log.info("collectMaxCountUser MCU Log Save logDay: {}, MaxCountUser: {}", logDay, mcuLog.getMaxCountUser());
            saveStatLogData(mcuLog);
        }

    }

    private void saveStatLogData(IndicatorsLog indicatorsLog) {

        if (indicatorsLog instanceof McuLogInfo) {
            McuLogInfo mcuLogInfo = (McuLogInfo) indicatorsLog;
            try {
                mcuRepository.save(mcuLogInfo);
            } catch (Exception e) {
                log.error("Error Repository Write MCUInfo: {}, Message: {}", mcuLogInfo, e.getMessage());
            }
        } else {
            log.error("Not instanceof McuLogInfo");
        }

    }

//    public McuLogInfo getMcuLogData(LocalDate date) {
//        try {
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            String logDay = date.format(formatter);
//            List<McuLogInfo> mcuLogInfo = mcuRepository.findByLogDay(logDay);
//            if (mcuLogInfo == null) {
//                log.info("No MCU data found for date: {}", logDay);
//                return null;
//            }
//            return mcuLogInfo.isEmpty() ? null : mcuLogInfo.get(0);
//        } catch (Exception e) {
//            log.error("Error while fetching MCU for date: {}", date, e);
//            throw e;
//        }
//    }
}
