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

import com.caliverse.admin.Indicators.Indicatordomain.IndicatorsLog;
import com.caliverse.admin.Indicators.entity.MauLogInfo;
import com.caliverse.admin.Indicators.indicatorrepository.IndicatorMauRepository;
import com.caliverse.admin.logs.Indicatordomain.MauMongoLog;
import com.caliverse.admin.logs.logservice.businesslogservice.BusinessLogMauService;
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 IndicatorsMauService{

    @Autowired private IndicatorMauRepository mauRepository;
    @Autowired private BusinessLogMauService businessLogMauService;

    public void collectMonthlyActiveUser(String startTime, String endTime){
        String logTimeStr = startTime.substring(0, 10);
        List<MauMongoLog> indicatorLog = businessLogMauService.loadBusinessLogData(startTime, endTime, MauMongoLog.class);

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

            MauLogInfo mauLog = new MauLogInfo(logDay, mongo_log.getAccountIdListCount());
            log.info("collectMonthlyActiveUser MAU Log Save logDay: {}, mau: {}", logDay, mauLog.getMau());
            saveStatLogData(mauLog);
        }
    }


    protected void saveStatLogData(IndicatorsLog indicatorsLog) {
        if (indicatorsLog instanceof MauLogInfo mau_log_info) {
            try {
                mauRepository.save(mau_log_info);
            } catch (Exception e) {
                log.error("Error Repository Write MAUInfo: {}, Message: {}", mau_log_info, e.getMessage());
            }
        } else {
            log.error("Not instanceof DauLogInfo");
        }
    }
}
