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

import com.caliverse.admin.Indicators.Indicatordomain.IndicatorsLog;
import com.caliverse.admin.Indicators.entity.PlayTimeLogInfo;
import com.caliverse.admin.Indicators.indicatorrepository.IndicatorPlayTimRepository;
import com.caliverse.admin.logs.Indicatordomain.PlayTimeMongoLog;
import com.caliverse.admin.logs.logservice.businesslogservice.BusinessLogPlayTimeService;
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 IndicatorsPlayTimeService{

    @Autowired private BusinessLogPlayTimeService businessLogPlayTimeService;
    @Autowired private IndicatorPlayTimRepository playTimeRepository;

    public void collectUserPlayTime(String startTime, String endTime){
        String logTimeStr = startTime.substring(0, 10);
        List<PlayTimeMongoLog> indicatorsLog = businessLogPlayTimeService.loadBusinessLogData(startTime, endTime, PlayTimeMongoLog.class);

        try {
            if (indicatorsLog == null || indicatorsLog.isEmpty()) {
                PlayTimeLogInfo playTimeLog = new PlayTimeLogInfo(logTimeStr, 0L);
                log.info("collectUserPlayTime PlayTime Log Save logDay: {}, TotalPlayTimeCount: {}", logTimeStr, playTimeLog.getTotalPlayTimeCount());
                saveStatLogData(playTimeLog);
                return;
            }

            for (PlayTimeMongoLog mongoLog : indicatorsLog) {
                String logDay = mongoLog.getLogDay();

                PlayTimeLogInfo playTimeLog = new PlayTimeLogInfo(logDay, mongoLog.getTotalPlayTimeCount());
                log.info("collectUserPlayTime PlayTime Log Save logDay: {}, TotalPlayTimeCount: {}", logDay, playTimeLog.getTotalPlayTimeCount());
                saveStatLogData(playTimeLog);
            }
        }catch (Exception e){
            log.error("collectUserPlayTime Error Message: {}", e.getMessage());
        }
    }

    public void saveStatLogData(IndicatorsLog indicatorsLog) {

        if (indicatorsLog instanceof PlayTimeLogInfo playTimeLogInfo) {
            try {
                playTimeRepository.save(playTimeLogInfo);
            } catch (Exception e) {
                log.error("saveStatLogData: {}", e.getMessage());
            }
        } else {
            log.error("Not instanceof PlayTimeLogiInfo");
        }
    }
}
