package cn.axzo.msg.center.service.pending.response;

import cn.axzo.basics.common.util.AssertUtil;
import cn.azxo.framework.common.model.Page;
import lombok.Getter;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Supplier;

/**
 * @author yanglin
 */
@Getter
public class AnalysisPage<T> extends Page<T> {

    private TreeMap<String, Object> analysis = new TreeMap<>();
    private boolean enableAnalysis;

    public AnalysisPage() {
    }

    public AnalysisPage(Long pageNum, Long pageSize, Long totalElements, List<T> list) {
        super(pageNum, pageSize, totalElements, list);
    }

    public static <T> AnalysisPage<T> toPage(Long pageNum, Long pageSize, Long totalCount, List<T> list) {
        return new AnalysisPage<>(pageNum, pageSize, totalCount, list);
    }

    public static <T> AnalysisPage<T> emptyPage(Long pageNum, Long pageSize) {
        return toPage(pageNum, pageSize, 0L, Collections.emptyList());
    }

    public <K> AnalysisPage<K> copyAs(List<K> items) {
        AnalysisPage<K> copy = new AnalysisPage<>(
                getPageNum(), getPageSize(), getTotalElements(), items);
        copy.setEnableAnalysis(enableAnalysis);
        return copy;
    }

    public void addAnalysis(Map<String, Object> analysis) {
        if (enableAnalysis)
            this.analysis.putAll(analysis);
    }

    public void addAnalysis(String key, Object value) {
        if (enableAnalysis && key != null && value != null)
            analysis.put(key, value);
    }

    /**
     * 添加查询成本较高的分析数据
     */
    public void addAnalysis(String key, Supplier<Object> provider) {
        if (enableAnalysis) {
            Object value = provider.get();
            if (value != null)
                analysis.put(key, value);
        }
    }

    public void addAnalysis(String key, Object... fields) {
        if (!enableAnalysis) return;
        AssertUtil.notNull(fields, "Fields can't be null");
        AssertUtil.isTrue(fields.length % 2 == 0, "The length of fields must be an integer multiple of 2");
        Map<String, Object> fieldsObj = new HashMap<>();
        for (int i = 0; i < fields.length; i += 2)
            fieldsObj.put(String.valueOf(fields[i]), fields[i + 1]);
        addAnalysis(key, fieldsObj);
    }

    public void setAnalysis(TreeMap<String, Object> analysis) {
        this.analysis = analysis;
    }

    public void setEnableAnalysis(boolean enableAnalysis) {
        this.enableAnalysis = enableAnalysis;
    }
}