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

import com.caliverse.admin.Indicators.Indicatordomain.IndicatorsLog;
import com.caliverse.admin.Indicators.entity.WauLogInfo;
import com.caliverse.admin.Indicators.indicatorrepository.IndicatorWauRepository;
import com.caliverse.admin.logs.Indicatordomain.WauMongoLog;
import com.caliverse.admin.logs.logservice.businesslogservice.BusinessLogWauService;
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 IndicatorsWauService{

    @Autowired private IndicatorWauRepository wauRepository;
    @Autowired private BusinessLogWauService businessLogWauService;

    public void collectWeeklyActiveUser(String startTime, String endTime){
        String logTimeStr = startTime.substring(0, 10);
        List<WauMongoLog> indicatorLog = businessLogWauService.loadBusinessLogData(startTime, endTime, WauMongoLog.class);

        try {
            if (indicatorLog == null || indicatorLog.isEmpty()) {
                WauLogInfo wauLog = new WauLogInfo(logTimeStr, 0);
                log.info("collectWeeklyActiveUser WAU Log Save logDay: {}, Wau: {}", logTimeStr, wauLog.getWau());
                saveStatLogData(wauLog);
                return;
            }

            for(WauMongoLog mongo_log : indicatorLog){
                String logDay = mongo_log.getLogDay();

                WauLogInfo wauLog = new WauLogInfo(logDay, mongo_log.getAccountIdListCount());
                log.info("collectWeeklyActiveUser WAU Log Save logDay: {}, Wau: {}", logDay, wauLog.getWau());
                saveStatLogData(wauLog);
            }
        }catch (Exception e){
            log.error("collectWeeklyActiveUser Error Message: {}", e.getMessage());
        }
    }

    public void saveStatLogData(IndicatorsLog indicatorsLog) {

        if (indicatorsLog instanceof WauLogInfo) {
            WauLogInfo wauLogInfo = (WauLogInfo) indicatorsLog;
            try {
                wauRepository.save(wauLogInfo);
            } catch (Exception e) {
                log.error("Error Repository Write WAUInfo: {}, Message: {}", wauLogInfo, e.getMessage());
            }
        } else {
            log.error("Not instanceof WauLogInfo");
        }
    }
}
