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

import com.jay.monitor.data.server.enums.DataSplitType;
import com.jay.monitor.data.server.factory.callback.IdChangeCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Module 生成器工厂
 * @Description 将所有生成器规则统一由生成器管理, 对外引用
 * @Author liukaixiong
 * @Date 2020/11/5 15:03
 */
public class DataIdFactory implements InitializingBean {

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

    private List<IdGenerateService> idGenerateServices;

    private Map<DataSplitType, IdGenerateService> idGenerateServiceMap;

    private IdChangeCallback idChangeCallback;

    public DataIdFactory(List<IdGenerateService> idGenerateServices, IdChangeCallback idChangeCallback) {
        this.idGenerateServices = idGenerateServices;
        this.idChangeCallback = idChangeCallback;
    }

    /**
     * 获取当前的生成id
     *
     * @param splitType
     * @return
     */
    public String getCurrentId(DataSplitType splitType) {
        if (idGenerateServiceMap != null) {
            IdGenerateService idGenerateService = idGenerateServiceMap.get(splitType);
            if (idGenerateService != null) {
                return idGenerateService.getCurrentId((id) -> {
                    try {
                        if (this.idChangeCallback != null) {
                            logger.info("触发id变更修改，ID的类型：" + splitType);
                            idChangeCallback.onChange(splitType, id);
                        } else {
                            logger.warn("没有找到对应的数据拆分处理规则:" + splitType);
                        }
                        logger.info("类型:" + splitType + "最后的编号:" + id);
                    } catch (Exception e) {
                        logger.error("数据生成失败", e);
                    }
                });
            }
        }
        return null;
    }

    public List<IdGenerateService> getIdGenerateServices() {
        return idGenerateServices;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (idGenerateServices != null) {
            idGenerateServiceMap = new HashMap<>();
            idGenerateServices.forEach((service) -> {
                idGenerateServiceMap.put(service.splitType(), service);
            });
        }
    }
}
