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

import com.caliverse.admin.global.common.constants.AdminConstants;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BusinessLogUserItemHistoryService extends BusinessLogServiceBase {

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

    }

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


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

        //여기서 stackCount랑, 로그 타입이랑 같이 가져와야 된다... 나중에 준비되명 하자.....



        ProjectionOperation pjt = Aggregation.project()
                .and(AdminConstants.MONGO_DB_KEY_USER_GUID).as(AdminConstants.MONGO_DB_KEY_USER_GUID)
                .and(AdminConstants.MONGO_DB_KEY_LOGTIME).as(AdminConstants.MONGO_DB_KEY_LOGTIME)
                ;
        operations.add(pjt);


        Aggregation aggregation = Aggregation.newAggregation(operations);
        AggregationResults<T> results = getMongoTemplate().aggregate(aggregation, AdminConstants.MONGO_DB_COLLECTION_LOG, clazz);
        return results.getMappedResults();
    }


    protected Criteria makeCriteria(String startTime, String endTime, String userGuid) {
        String regex = "\"UserGuid\":\"" + userGuid + "\"";
        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(regex)
                    )
            );
    }


}
