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

import com.caliverse.admin.global.common.constants.AdminConstants;
import com.mongodb.BasicDBObject;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Sort;
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 BusinessLogUserLoginService extends BusinessLogServiceBase {


    public BusinessLogUserLoginService(@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("$addFields",
                        new Document(AdminConstants.MONGO_DB_KEY_LOGIN_TIME,
                                new Document("$let",
                                        new Document("vars",
                                                new Document("found",
                                                        new Document("$regexFind",
                                                                new Document("input", "$message")
                                                                        .append("regex", "\"LoginTime\":\"([^\"]+)\"")
                                                        )
                                                )
                                        ).append("in",
                                                new Document("$arrayElemAt", Arrays.asList("$$found.captures", 0))
                                        )
                                )
                        ).append(AdminConstants.MONGO_DB_KEY_LOGOUT_TIME,
                                new Document("$let",
                                        new Document("vars",
                                                new Document("found",
                                                        new Document("$regexFind",
                                                                new Document("input", "$message")
                                                                        .append("regex", "\"LogoutTime\":\"([^\"]+)\"")
                                                        )
                                                )
                                        ).append("in",
                                                new Document("$arrayElemAt", Arrays.asList("$$found.captures", 0))
                                        )
                                )
                        ).append(AdminConstants.MONGO_DB_KEY_IP,
                                new Document("$let",
                                        new Document("vars",
                                                new Document("found",
                                                        new Document("$regexFind",
                                                                new Document("input", "$message")
                                                                        .append("regex", "\"Ip\":\"([^\"]+)\"")
                                                        )
                                                )
                                        ).append("in",
                                                new Document("$arrayElemAt", Arrays.asList("$$found.captures", 0))
                                        )
                                )
                        )
                )
        );

        operations.add(context ->
                new Document("$match",
                        new Document("$expr",
                                new Document("$and", Arrays.asList(
                                        new Document("$not",
                                                new Document("$regexMatch",
                                                        new Document("input", new Document("$toString", "$loginTime"))
                                                                .append("regex", "^(0001|1970|3000)")
                                                )
                                        ),
                                        new Document("$not",
                                                new Document("$regexMatch",
                                                        new Document("input", new Document("$toString", "$serverType"))
                                                                .append("regex", "^Login")
                                                )
                                        )
                                ))
                        )
                )
        );

        operations.add(context ->
                new Document("$addFields",
                        new Document("loginTimeDate",
                                new Document("$dateFromString",
                                        new Document("dateString",
                                                new Document("$substr", Arrays.asList("$loginTime", 0, 19))
                                        ).append("format", "%Y-%m-%dT%H:%M:%S")
                                )
                        ).append("logoutTimeDate",
                                new Document("$dateFromString",
                                        new Document("dateString",
                                                new Document("$substr", Arrays.asList("$logoutTime", 0, 19))
                                        ).append("format", "%Y-%m-%dT%H:%M:%S")
                                )
                        )
                )
        );

        operations.add(context ->
                new Document("$addFields",
                        new Document("playTimeInSeconds",
                                new Document("$divide", Arrays.asList(
                                        new Document("$subtract", Arrays.asList(
                                                new Document("$toDate", "$logoutTimeDate"),
                                                new Document("$toDate", "$loginTimeDate")
                                        ))
                                        , 1000
                                ))
                        )
                )
        );

        SortOperation sortOperation = Aggregation.sort(
                Sort.by(
                        Sort.Order.asc(AdminConstants.MONGO_DB_KEY_ACCOUNT_ID),
                        Sort.Order.asc(AdminConstants.MONGO_DB_KEY_LOGTIME)
                )
        );
        operations.add(sortOperation);

        operations.add(context ->
                new Document("$group",
                        new Document("_id",
                                new Document(AdminConstants.MONGO_DB_KEY_LOGDAY, "$logDay")
                                        .append(AdminConstants.MONGO_DB_KEY_ACCOUNT_ID, "$accountId")
                        )
                                .append(AdminConstants.MONGO_DB_KEY_LOGDAY, new Document("$first", "$logDay"))
                                .append(AdminConstants.MONGO_DB_KEY_ACCOUNT_ID, new Document("$first", "$accountId"))
                                .append(AdminConstants.MONGO_DB_KEY_USER_GUID, new Document("$first", "$userGuid"))
                                .append(AdminConstants.MONGO_DB_KEY_USER_NICKNAME, new Document("$max", "$userNickname"))
                                .append("sessions", new Document("$push",
                                        new Document(AdminConstants.MONGO_DB_KEY_ACTION, "$action")
                                                .append(AdminConstants.MONGO_DB_KEY_SERVER_TYPE, "$serverType")
                                                .append(AdminConstants.MONGO_DB_KEY_LOGIN_TIME, "$loginTimeDate")
                                                .append(AdminConstants.MONGO_DB_KEY_LOGOUT_TIME, "$logoutTimeDate")
                                                .append(AdminConstants.MONGO_DB_KEY_TRAN_ID, "$tranId")
                                                .append(AdminConstants.MONGO_DB_COLLECTION_PLAYTIME, "$playTimeInSeconds")
                                                .append(AdminConstants.MONGO_DB_KEY_IP, "$ip")
                                                .append(AdminConstants.MONGO_DB_KEY_LANGUAGE_TYPE, "$languageType")
                                ))
                                .append("firstLoginTime", new Document("$min", "$loginTimeDate"))
                                .append("lastLogoutTime", new Document("$max", "$logoutTimeDate"))
                                .append("loginCount", new Document("$sum", 1))
                                .append("totalPlayTime", new Document("$sum", "$playTimeInSeconds"))
                )
        );

        // 최종 출력 형식
        operations.add(context ->
                new Document("$project",
                        new Document(AdminConstants.MONGO_DB_KEY_LOGDAY, "$logDay")
                                .append(AdminConstants.MONGO_DB_KEY_ACCOUNT_ID, "$accountId")
                                .append(AdminConstants.MONGO_DB_KEY_USER_GUID, 1)
                                .append(AdminConstants.MONGO_DB_KEY_USER_NICKNAME, 1)
                                .append("sessions", 1)
                                .append("firstLoginTime", 1)
                                .append("lastLogoutTime", 1)
                                .append("loginCount", 1)
                                .append("totalPlayTime", 1)
                                .append("_id", 0)
                )
        );

        AggregationOptions options = AggregationOptions.builder()
                .allowDiskUse(true)
                .build();
        Aggregation aggregation = Aggregation.newAggregation(operations).withOptions(options);
        log.info("loadBusinessLogData UserLogin 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_USER_LOGOUT)
                                )
                        // AccountId가 빈값인 경우 제외
                        , Criteria.where(AdminConstants.MONGO_DB_KEY_MESSAGE).not().regex("\"AccountId\"\\s*:\\s*\"\"")
                );
    }
}
