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

import com.caliverse.admin.global.common.constants.AdminConstants;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class BusinessLogDglcService extends BusinessLogServiceBase {

    public BusinessLogDglcService(@Qualifier("mongoBusinessLogTemplate") MongoTemplate mongoTemplate) {
        super(mongoTemplate);
    }

    public <T> List<T> loadBusinessLogData(String startTime, String endTime, Class<T> class1) {

        Criteria criteria = makeCriteria(startTime, endTime);
        List<AggregationOperation> operations = setDefaultOperation(criteria);

        //그룹화
        operations.add(context ->
                new Document("$group",
                        new Document("_id", "$logDay")
                                .append("logDay", new Document("$first", "$logDay"))
                                .append("totalCount",
                                        new Document("$sum", 1)
                                )
                ));

        Aggregation aggregation = Aggregation.newAggregation(operations);
        log.info("loadBusinessLogData DGLC Query: {}", aggregation);
        AggregationResults<T> results = getMongoTemplate()
                .aggregate(aggregation, AdminConstants.MONGO_DB_COLLECTION_LOG, class1);

        return results.getMappedResults();
    }

    protected Criteria makeCriteria(String startTime, String endTime) {
        return new Criteria()
                .andOperator(
                        Criteria.where(AdminConstants.MONGO_DB_KEY_LOGTIME).gte(startTime)
                        ,Criteria.where(AdminConstants.MONGO_DB_KEY_LOGTIME).lt(endTime)
                        , new Criteria()
                                .orOperator(
                                        Criteria.where(AdminConstants.MONGO_DB_KEY_MESSAGE).regex(AdminConstants.REGEX_MSG_LOGIN_TO_GAME)
                                )
                );
    }
}
