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

import com.caliverse.admin.Indicators.Indicatordomain.IndicatorsLog;
import com.caliverse.admin.Indicators.entity.DglcLogInfo;
import com.caliverse.admin.Indicators.indicatorrepository.IndicatorDglcRepository;
import com.caliverse.admin.logs.Indicatordomain.DglcMongoLog;
import com.caliverse.admin.logs.logservice.businesslogservice.BusinessLogDglcService;
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 IndicatorsDglcService{

    @Autowired private BusinessLogDglcService businessLogDglcService;
    @Autowired private IndicatorDglcRepository dglcRepository;


    public void collectDailyGameLoginCount(String startTime, String endTime){
        String logTimeStr = startTime.substring(0, 10);
        List<DglcMongoLog> indicatorsLog = businessLogDglcService.loadBusinessLogData(startTime, endTime, DglcMongoLog.class);

        if (indicatorsLog == null || indicatorsLog.isEmpty()) {
            DglcLogInfo dglcLog = new DglcLogInfo(logTimeStr, 0);
            log.info("collectDailyGameLoginCount DGLC Log Save logDay: {}, TotalCount: {}", logTimeStr, dglcLog.getDglc());
            saveStatLogData(dglcLog);
            return;
        }

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

            DglcLogInfo dglcLog = new DglcLogInfo(logDay, mongo_log.getTotalCount());
            log.info("collectDailyGameLoginCount DGLC Log Save logDay: {}, TotalCount: {}", logDay, dglcLog.getDglc());
            saveStatLogData(dglcLog);
        }
    }

    public void saveStatLogData(IndicatorsLog indicatorsLog) {

        if (indicatorsLog instanceof DglcLogInfo dglcLogInfo) {
            try {
                dglcRepository.save(dglcLogInfo);
            } catch (Exception e) {
                log.error("Error Repository Write DGLCInfo: {}, Message: {}", dglcLogInfo, e.getMessage());
            }
        } else {
            log.error("Not instanceof DglcLogiInfo");
        }
    }
}
