package org.wcs.plugin.plc;

import lombok.extern.slf4j.Slf4j;
import org.wcs.constant.enums.database.PlcTypeEnum;
import org.wcs.mapper.intf.AppBasePlcService;
import org.wcs.model.po.app.AppBasePlc;
import org.wcs.plugin.plc.communication.IPlcCommunication;
import org.wcs.plugin.plc.communication.PlcSiemensCommunication;
import org.wcs.utils.SpringUtils;

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

@Slf4j
public class PlcCommunicationFactory {


    /**
     * PLC通讯对象 <PLCID，PLC通讯类>
     */
    private static Map<Integer, IPlcCommunication> plcCommunicationMap;



    /**
     * 通过PLCID获取PLC通讯对象
     *
     * @param plcId PLCID
     * @return PLC通讯对象 --- 若不存在则返回西门子方法
     */
    public static IPlcCommunication getPlcCommunicationByPlcId(Integer plcId) {
        setPlcCommunicationMap(); // 初始化PLC通讯对象
        if(plcId == null) {
            throw new NullPointerException("PLCID不能为空");
        }
        if(plcCommunicationMap.containsKey(plcId)) {
            return plcCommunicationMap.get(plcId);
        }
        throw new NullPointerException("找不到该ID的连接");
    }


    /* ****************************** 初始化时加载数据方法 ************************************** */

    /**
     * 加载PLC通讯对象
     */
    private static void setPlcCommunicationMap() {
        if(plcCommunicationMap == null || plcCommunicationMap.isEmpty()) {
            plcCommunicationMap = new HashMap<>();
        } else  {
            return;
        }
        AppBasePlcService bean = SpringUtils.getBean(AppBasePlcService.class);
        List<AppBasePlc> basePlcList = bean.queryAll();
        if(basePlcList == null) {
            log.info("初始化PLC连接时查询PLC信息失败");
            return;
        }
        for (AppBasePlc plcItem : basePlcList) {
            // 创建PLC操作对象
            Integer plcType = plcItem.getPlcType();
            if(plcType == null) {
                continue;
            }
            if(plcType.equals(PlcTypeEnum.SIEMENS.getCode())) {
                log.info("初始化PLC连接：PLCID：{}，PLC名称：{}，PLC类型：{}", plcItem.getPlcId(), plcItem.getPlcName(), PlcTypeEnum.SIEMENS.getMessage());
                IPlcCommunication plcCommunication = new PlcSiemensCommunication();
                plcCommunication.initialize(plcItem);
                plcCommunicationMap.put(plcItem.getPlcId(), plcCommunication);
            }
        }
    }

    /* ****************************** 初始化时加载数据方法 END ************************************** */



}
