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.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class BusinessLogCurrencyService extends BusinessLogServiceBase {

    public BusinessLogCurrencyService(@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", "$tranId")
                                .append("logDay", new Document("$first", "$logDay"))
                                .append("logTime", new Document("$first", "$logTime"))
                                .append("userGuid", new Document("$first", "$userGuid"))
                                .append("userNickname", new Document("$first", "$userNickname"))
                                .append("accountId", new Document("$first", "$accountId"))
                                .append("action", new Document("$first", "$action"))
                                .append("documents", new Document("$push", "$$ROOT"))
                )
        );

        operations.add(context ->
                new Document("$match",
                        new Document("documents",
                                new Document("$elemMatch",
                                        new Document("message",
                                                new Document("$regex", "\"Domain\":\"Currency\"")
                                        )
                                )
                        )
                )
        );

        operations.add(context ->
                new Document("$sort",
                        new Document("logTime", 1)
                )
        );

        operations.add(context ->
                new Document("$addFields",
                        new Document("currencyDocuments",
                                new Document("$filter",
                                        new Document("input", "$documents")
                                                .append("as", "doc")
                                                .append("cond",
                                                        new Document("$regexMatch",
                                                                new Document("input", "$$doc.message")
                                                                        .append("regex", "\"Domain\":\"Currency\"")
                                                        )
                                                )
                                )
                        )
                )
        );

        operations.add(context ->
                new Document("$addFields",
                        new Document("currencyInfo",
                                new Document("$map",
                                        new Document("input", "$currencyDocuments")
                                                .append("as", "doc")
                                                .append("in",
                                                        new Document("currencyType",
                                                                new Document("$let",
                                                                        new Document("vars",
                                                                                new Document("found",
                                                                                        new Document("$regexFind",
                                                                                                new Document("input", "$$doc.message")
                                                                                                        .append("regex", "\"CurrencyType\":\"([^\"]+)\"")
                                                                                        )
                                                                                )
                                                                        )
                                                                                .append("in",
                                                                                        new Document("$arrayElemAt",
                                                                                                Arrays.asList("$$found.captures", 0)
                                                                                        )
                                                                                )
                                                                )
                                                        )
                                                                .append("amountDeltaType",
                                                                        new Document("$let",
                                                                                new Document("vars",
                                                                                        new Document("found",
                                                                                                new Document("$regexFind",
                                                                                                        new Document("input", "$$doc.message")
                                                                                                                .append("regex", "\"AmountDeltaType\":\"([^\"]+)\"")
                                                                                                )
                                                                                        )
                                                                                )
                                                                                        .append("in",
                                                                                                new Document("$arrayElemAt",
                                                                                                        Arrays.asList("$$found.captures", 0)
                                                                                                )
                                                                                        )
                                                                        )
                                                                )
                                                                .append("deltaAmount",
                                                                        new Document("$let",
                                                                                new Document("vars",
                                                                                        new Document("found",
                                                                                                new Document("$regexFind",
                                                                                                        new Document("input", "$$doc.message")
                                                                                                                .append("regex", "\"DeltaAmount\":([^,}]+)")
                                                                                                )
                                                                                        )
                                                                                )
                                                                                        .append("in",
                                                                                                new Document("$toDouble",
                                                                                                        new Document("$arrayElemAt",
                                                                                                                Arrays.asList("$$found.captures", 0)
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                        )
                                                                )
                                                                .append("currencyAmount",
                                                                        new Document("$let",
                                                                                new Document("vars",
                                                                                        new Document("found",
                                                                                                new Document("$regexFind",
                                                                                                        new Document("input", "$$doc.message")
                                                                                                                .append("regex", "\"CurrencyAmount\":([^,}]+)")
                                                                                                )
                                                                                        )
                                                                                )
                                                                                        .append("in",
                                                                                                new Document("$toDouble",
                                                                                                        new Document("$arrayElemAt",
                                                                                                                Arrays.asList("$$found.captures", 0)
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                        )
                                                                )
                                                )
                                )
                        )
                )
        );

        operations.add(context ->
                new Document("$unwind", "$currencyInfo")
        );

        operations.add(context ->
                new Document("$match",
                        new Document("currencyInfo.currencyType",
                                new Document("$ne", null)
                        )
                                .append("currencyInfo.amountDeltaType",
                                        new Document("$ne", null)
                                )
                                .append("currencyInfo.deltaAmount",
                                        new Document("$ne", null)
                                )
                )
        );

        operations.add(context ->
                new Document("$group",
                        new Document("_id",
                                new Document("logDay", "$logDay")
                                        .append("accountId", "$accountId")
                        )
                                .append("userGuid", new Document("$first", "$userGuid"))
                                .append("userNickname", new Document("$first", "$userNickname"))

                                // Gold
                                .append("goldAcquired",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Gold")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Acquire"))
                                                                        )
                                                                ),
                                                                "$currencyInfo.deltaAmount",
                                                                0
                                                        )
                                                )
                                        )
                                )
                                .append("goldConsumed",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Gold")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Consume"))
                                                                        )
                                                                ),
                                                                new Document("$abs", "$currencyInfo.deltaAmount"),
                                                                0
                                                        )
                                                )
                                        )
                                )

                                // Sapphire
                                .append("sapphireAcquired",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Sapphire")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Acquire"))
                                                                        )
                                                                ),
                                                                "$currencyInfo.deltaAmount",
                                                                0
                                                        )
                                                )
                                        )
                                )
                                .append("sapphireConsumed",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Sapphire")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Consume"))
                                                                        )
                                                                ),
                                                                new Document("$abs", "$currencyInfo.deltaAmount"),
                                                                0
                                                        )
                                                )
                                        )
                                )

                                // Calium
                                .append("caliumAcquired",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Calium")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Acquire"))
                                                                        )
                                                                ),
                                                                "$currencyInfo.deltaAmount",
                                                                0
                                                        )
                                                )
                                        )
                                )
                                .append("caliumConsumed",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Calium")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Consume"))
                                                                        )
                                                                ),
                                                                new Document("$abs", "$currencyInfo.deltaAmount"),
                                                                0
                                                        )
                                                )
                                        )
                                )

                                // Beam
                                .append("beamAcquired",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Beam")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Acquire"))
                                                                        )
                                                                ),
                                                                "$currencyInfo.deltaAmount",
                                                                0
                                                        )
                                                )
                                        )
                                )
                                .append("beamConsumed",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Beam")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Consume"))
                                                                        )
                                                                ),
                                                                new Document("$abs", "$currencyInfo.deltaAmount"),
                                                                0
                                                        )
                                                )
                                        )
                                )

                                // Ruby
                                .append("rubyAcquired",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Ruby")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Acquire"))
                                                                        )
                                                                ),
                                                                "$currencyInfo.deltaAmount",
                                                                0
                                                        )
                                                )
                                        )
                                )
                                .append("rubyConsumed",
                                        new Document("$sum",
                                                new Document("$cond",
                                                        Arrays.asList(
                                                                new Document("$and",
                                                                        Arrays.asList(
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.currencyType", "Ruby")),
                                                                                new Document("$eq", Arrays.asList("$currencyInfo.amountDeltaType", "Consume"))
                                                                        )
                                                                ),
                                                                new Document("$abs", "$currencyInfo.deltaAmount"),
                                                                0
                                                        )
                                                )
                                        )
                                )

                                .append("totalCurrencies", new Document("$sum", 1))
                                .append("currencies",
                                        new Document("$push",
                                                new Document("tranId", "$_id")
                                                        .append("action", "$action")
                                                        .append("logTime", "$logTime")
                                                        .append("currencyType", "$currencyInfo.currencyType")
                                                        .append("amountDeltaType", "$currencyInfo.amountDeltaType")
                                                        .append("deltaAmount", "$currencyInfo.deltaAmount")
                                                        .append("currencyAmount", "$currencyInfo.currencyAmount")
                                        )
                                )
                )
        );

        operations.add(context ->
                new Document("$project",
                        new Document("_id", 0)
                                .append("logDay", "$_id.logDay")
                                .append("accountId", "$_id.accountId")
                                .append("userGuid", 1)
                                .append("userNickname", 1)
                                .append("goldAcquired", 1)
                                .append("goldConsumed", 1)
                                .append("goldNet",
                                        new Document("$subtract",
                                                Arrays.asList("$goldAcquired", "$goldConsumed")
                                        )
                                )
                                .append("sapphireAcquired", 1)
                                .append("sapphireConsumed", 1)
                                .append("sapphireNet",
                                        new Document("$subtract",
                                                Arrays.asList("$sapphireAcquired", "$sapphireConsumed")
                                        )
                                )
                                .append("caliumAcquired", 1)
                                .append("caliumConsumed", 1)
                                .append("caliumNet",
                                        new Document("$subtract",
                                                Arrays.asList("$caliumAcquired", "$caliumConsumed")
                                        )
                                )
                                .append("beamAcquired", 1)
                                .append("beamConsumed", 1)
                                .append("beamNet",
                                        new Document("$subtract",
                                                Arrays.asList("$beamAcquired", "$beamConsumed")
                                        )
                                )
                                .append("rubyAcquired", 1)
                                .append("rubyConsumed", 1)
                                .append("rubyNet",
                                        new Document("$subtract",
                                                Arrays.asList("$rubyAcquired", "$rubyConsumed")
                                        )
                                )
                                .append("totalCurrencies", 1)
                                .append("currencies", 1)
                )
        );

        operations.add(context ->
                new Document("$sort",
                        new Document("logTime", 1)
                                .append("accountId", 1)
                )
        );

        Aggregation aggregation = Aggregation.newAggregation(operations);
        log.info("loadBusinessLogData Currency Query: {}", aggregation);
        AggregationResults<T> results = getMongoTemplate().aggregate(
                aggregation.withOptions(AggregationOptions.builder().allowDiskUse(true).build())
                , 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)
                );
    }
}
