package com.purui.prims.headless.chat.utils;

import com.purui.prims.common.pojo.enums.QueryType;
import com.purui.prims.common.pojo.enums.TimeMode;
import com.purui.prims.common.util.DatePeriodEnum;
import com.purui.prims.common.util.DateUtils;
import com.purui.prims.headless.chat.ChatQueryContext;
import com.purui.prims.headless.api.pojo.DataSetSchema;
import com.purui.prims.headless.api.pojo.TimeDefaultConfig;
import org.apache.commons.lang3.tuple.Pair;

import java.util.Objects;

public class S2SqlDateHelper {

    public static String getReferenceDate(ChatQueryContext queryContext, Long dataSetId) {
        String defaultDate = DateUtils.getBeforeDate(0);
        if (Objects.isNull(dataSetId)) {
            return defaultDate;
        }
        DataSetSchema dataSetSchema = queryContext.getSemanticSchema().getDataSetSchemaMap().get(dataSetId);
        return getDefaultDate(defaultDate, dataSetSchema.getMetricTypeTimeDefaultConfig()).getLeft();
    }

    public static Pair<String, String> getStartEndDate(ChatQueryContext queryContext, Long dataSetId,
                                                       QueryType queryType) {
        String defaultDate = DateUtils.getBeforeDate(0);
        if (Objects.isNull(dataSetId)) {
            return Pair.of(defaultDate, defaultDate);
        }
        DataSetSchema dataSetSchema = queryContext.getSemanticSchema().getDataSetSchemaMap().get(dataSetId);
        if (dataSetSchema == null) {
            return Pair.of(defaultDate, defaultDate);
        }
        TimeDefaultConfig defaultConfig = dataSetSchema.getMetricTypeTimeDefaultConfig();
        if (QueryType.DETAIL.equals(queryType)) {
            defaultConfig = dataSetSchema.getMetricTypeTimeDefaultConfig();
        }
        return getDefaultDate(defaultDate, defaultConfig);
    }

    public static Pair<String, String> getDefaultDate(String defaultDate, TimeDefaultConfig defaultConfig) {
        if (Objects.isNull(defaultConfig)) {
            return Pair.of(null, null);
        }
        Integer unit = defaultConfig.getUnit();
        String period = defaultConfig.getPeriod();
        TimeMode timeMode = defaultConfig.getTimeMode();
        if (Objects.nonNull(unit)) {
            // If the unit is set to less than 0, then do not add relative date.
            if (unit < 0) {
                return Pair.of(null, null);
            }
            DatePeriodEnum datePeriodEnum = DatePeriodEnum.get(period);
            String startDate = DateUtils.getBeforeDate(unit, datePeriodEnum);
            String endDate = DateUtils.getBeforeDate(1, datePeriodEnum);
            if (unit == 0) {
                endDate = startDate;
            }
            if (TimeMode.LAST.equals(timeMode)) {
                endDate = startDate;
            }
            return Pair.of(startDate, endDate);
        }
        return Pair.of(defaultDate, defaultDate);
    }

}
