package com.jay.monitor.data.server.store;

import com.jay.monitor.data.server.enums.DataSplitType;
import com.jay.monitor.data.server.enums.StoreType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Module 管理器
 * @Description 数据拆分管理器
 * @Author liukaixiong
 * @Date 2020/11/5 18:40
 */
public class SplitDataManager implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private List<AbstractSplitDataProcess> splitDataProcessList;

    private Map<StoreType, AbstractSplitDataProcess> processMap = new ConcurrentHashMap<>();

    public SplitDataManager(List<AbstractSplitDataProcess> splitDataProcessList) {
        this.splitDataProcessList = splitDataProcessList;
    }

    public void generateMysql(StoreType storeType, DataSplitType splitType) {
        generate(storeType, splitType);
    }

    /**
     * 生成事件
     *
     * @param storeType 存储类型 (MYSQL)
     * @param splitType 拆分类型
     */
    public void generate(StoreType storeType, DataSplitType splitType) {
        AbstractSplitDataProcess storeProcess = processMap.get(storeType);
        if (storeProcess != null) {
            storeProcess.splitDataInvoke(splitType);
        } else {
            logger.warn("找不到对应的[" + splitType + "]");
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.splitDataProcessList != null) {
            splitDataProcessList.forEach((bean) -> {
                processMap.put(bean.storeType(), bean);
            });
            Assert.isTrue(processMap.size() > 0, "找不到对应的存储器");
        }
    }

    /**
     * 希望重启的时候，能够触发方法构建存储结构
     */
    public void initFirstProcess() {
        try {
            DataSplitType[] splitTypes = DataSplitType.values();
            processMap.forEach((K, bean) -> {
                for (int i = 0; i < splitTypes.length; i++) {
                    DataSplitType dataSplitType = splitTypes[i];
                    bean.splitDataInvoke(dataSplitType);
                }
            });
        } catch (Exception e) {
            logger.warn("初始化拆分数据结构失败:" + e.getMessage());
        }
    }

}
