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

import com.caliverse.admin.Indicators.Indicatordomain.IndicatorsLog;
import com.caliverse.admin.Indicators.entity.UgqCreateLogInfo;
import com.caliverse.admin.Indicators.indicatorrepository.IndicatorUgqCreateRepository;
import com.caliverse.admin.logs.Indicatordomain.UgqCreateMongoLog;
import com.caliverse.admin.logs.logservice.businesslogservice.BusinessLogUgqCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class IndicatorsUgqCreateService {

    @Autowired private BusinessLogUgqCreateService businessLogUgqCreateService;
    @Autowired private IndicatorUgqCreateRepository ugqCreateRepository;


    public void collectUGQCreateCount(String startTime, String endTime){
        String logTimeStr = startTime.substring(0, 10);
        List<UgqCreateMongoLog> indicatorsLog = businessLogUgqCreateService.loadBusinessLogData(startTime, endTime, UgqCreateMongoLog.class);

        if (indicatorsLog == null || indicatorsLog.isEmpty()) {
            UgqCreateLogInfo ugqCreateLog = new UgqCreateLogInfo(logTimeStr, 0);
            log.info("collectUGQCreateCount ugqCreateLog Log Save logDay: {}, UGQCreateCount: {}", logTimeStr, ugqCreateLog.getUgqCrateCount());
            saveStatLogData(ugqCreateLog);
            return;
        }

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

            UgqCreateLogInfo ugqCreateLog = new UgqCreateLogInfo(logDay, mongo_log.getUgqCrateCount());
            log.info("collectUGQCreateCount ugqCreateLog Log Save logDay: {}, UGQCreateCount: {}", logDay, ugqCreateLog.getUgqCrateCount());
            saveStatLogData(ugqCreateLog);
        }
    }

    public void saveStatLogData(IndicatorsLog indicatorsLog) {

        if (indicatorsLog instanceof UgqCreateLogInfo ugqCreateLogInfo) {
            try {
                ugqCreateRepository.save(ugqCreateLogInfo);
            } catch (Exception e) {
                log.error("Error Repository Write UgqCreateLogInfo: {}, Message: {}", ugqCreateLogInfo, e.getMessage());
            }
        } else {
            log.error("Not instanceof UgqCreateLogInfo");
        }
    }
}
