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

import com.jay.monitor.data.core.enums.MsgTypeEnums;
import com.jay.monitor.data.core.model.serializable.base.BaseDTO;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

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

/**
 * @Module 存储
 * @Description 存储管理器
 * @Author liukaixiong
 * @Date 2020/10/29 13:30
 */
@Component
public class StoreDataManager implements InitializingBean {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private List<AbstractStoreProcess> storeProcessList;

    private StoreType storeType = StoreType.MYSQL;

    private Map<MsgTypeEnums, AbstractStoreProcess> processMap = new ConcurrentHashMap<>();

    public void setStoreType(StoreType storeType) {
        this.storeType = storeType;
    }

    public Object store(MsgTypeEnums msgType, BaseDTO baseDTO) throws Exception {
        AbstractStoreProcess storeProcess = processMap.get(msgType);
        if (storeProcess != null) {
            return storeProcess.store(baseDTO);
        } else {
            logger.warn("找不到对应的[" + storeType + "]存储处理器 : " + msgType);
        }
        return null;
    }

    public String selectContentById(MsgTypeEnums msgType, String date, String logId) throws Exception {
        AbstractStoreProcess storeProcess = processMap.get(msgType);
        if (storeProcess != null) {
            return storeProcess.searchContentById(date,logId);
        } else {
            logger.warn("找不到对应的[" + storeType + "]存储处理器 : " + msgType);
        }
        return null;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        storeProcessList.forEach((bean) -> {
            if (storeType == bean.storeType()) {
                processMap.put(bean.msgTypeEnums(), bean);
            }
        });

        Assert.isTrue(processMap.size() > 0, "找不到对应的存储器");
    }
}
