package com.jiayue.ipfcst.dataexchange.tunnelworker.gathers.iml;

import com.jiayue.ipfcst.common.data.constant.enums.DataSourceEnum;
import com.jiayue.ipfcst.common.data.constant.enums.TunnelStatus;
import com.jiayue.ipfcst.common.data.entity.ProtocolDataType;
import com.jiayue.ipfcst.common.data.entity.ProtocolGatherDataPoint;
import com.jiayue.ipfcst.common.data.entity.gathertunnelinfo.GatherCdtRtuTunnelInfo;
import com.jiayue.ipfcst.dataexchange.container.ProtocolTunnelContainer;
import com.jiayue.ipfcst.dataexchange.exception.DataExchangeException;
import com.jiayue.ipfcst.dataexchange.tunnelworker.BaseProtocolTunnel;
import com.jiayue.ipfcst.dataexchange.tunnelworker.gathers.DataGatherInterface;
import com.jiayue.ipfcst.dataexchange.tunnelworker.workassist.SingleThreadPoolExecutorUtil;
import com.jiayue.ipfcst.dataexchange.tunnelworker.workassist.cdt.MyCDTDataHandler;
import lombok.Getter;
import wei.yigulu.cdt.netty.CDTMaster;
import wei.yigulu.purejavacomm.PureJavaCommChannelConfig;

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

/**
 * cdt 协议 Rtu获取
 *
 * @author: xiuwei
 * @version:
 */
@SuppressWarnings("ALL")
public class CdtRtuDataGather extends BaseProtocolTunnel<GatherCdtRtuTunnelInfo> implements DataGatherInterface {


  /**
   * CDTMaster 对象 CDT协议00-f0是遥测  f0之后是遥信
   */
  CDTMaster cdtMaster;
  /**
   * 遥测点表
   */
  @Getter
  private Map<Integer, ProtocolGatherDataPoint> cdtYcDataPoints = new HashMap<>();
  /**
   * 遥信点表
   */
  @Getter
  private Map<Integer, ProtocolGatherDataPoint> cdtYxDataPoints = new HashMap<>();


  /**
   * 构造方法
   *
   * @param gatherCdtRtuTunnelInfo 通道信息
   */
  public CdtRtuDataGather(GatherCdtRtuTunnelInfo gatherCdtRtuTunnelInfo) {
    super(gatherCdtRtuTunnelInfo);
  }


  @Override
  public CdtRtuDataGather buildTunnel() throws DataExchangeException {
    parseGatherDataPoint();
    this.cdtMaster = new CDTMaster(getTunnelInfo().getSerialName(), new MyCDTDataHandler(this).setLog(log));
    this.cdtMaster.setLog(log);
    this.cdtMaster.setBaudRate(getTunnelInfo().getBaudRate()).setParity(PureJavaCommChannelConfig.Paritybit.valueOf(getTunnelInfo().getParity()));
    this.setTunnelStatus(TunnelStatus.BUILT);
    ProtocolTunnelContainer.getInstance().addTunnel(this);
    log.info("成功创建CDT  rtu Master通道对象：{}", this.tunnelInfo.getTunnelName());
    return this;
  }

  @Override
  public void parseGatherDataPoint() throws DataExchangeException {
    List<ProtocolGatherDataPoint> protocolGatherDataPoints = this.getTunnelInfo().getDataPoints();
    cdtYxDataPoints = new HashMap<>();
    cdtYcDataPoints = new HashMap<>();
    if (protocolGatherDataPoints == null || protocolGatherDataPoints.size() == 0) {
      return;
    }
    protocolGatherDataPoints.removeIf((o) -> {
      return o.getProtocolPointNo() == null || o.getDataSource()!= DataSourceEnum.GATHER;
    });
   // protocolGatherDataPoints.sort(Comparator.comparing(ProtocolGatherDataPoint::getProtocolPointNo));
    for (ProtocolGatherDataPoint p : protocolGatherDataPoints) {
      if (ProtocolDataType.A.equals(p.getProtocolPointType())) {
        cdtYxDataPoints.put(p.getProtocolPointNo(), p);
      } else {
        cdtYcDataPoints.put(p.getProtocolPointNo() , p);
      }
    }
    if (this.cdtMaster != null) {
      ((MyCDTDataHandler) this.cdtMaster.getDataHandler()).setCdtYcDataPoints(getCdtYcDataPoints()).setCdtYxDataPoints(getCdtYxDataPoints());
    }
  }


  @Override
  public BaseProtocolTunnel tunnelStop() throws DataExchangeException {
    if (this.cdtMaster != null) {
      cdtMaster.stop();
    }
    log.info("关闭 cdt Master 通道 {}", this.tunnelInfo.getTunnelName());
    return super.tunnelStop();
  }


  @Override
  public CdtRtuDataGather startTunnel() throws DataExchangeException {
    log.info("CDT RTU master {} 通道开始连接", getTunnelInfo().getTunnelName());
    protocolTunnelContainer.addUpdateDateTask(this);
    try {
      SingleThreadPoolExecutorUtil.executeBySingleThreadExecutor(() -> {
        this.cdtMaster.create();
        log.error("cdt rtu master 创建通道失败");
        setTunnelStatus(TunnelStatus.LISTENSERIALFAIL);
      });
    } catch (Exception e) {
      log.error("cdt rtu master 创建通道失败", e);
      setTunnelStatus(TunnelStatus.LISTENSERIALFAIL);
      throw new DataExchangeException(10007, "cdt rtu master创建通道失败");
    }
    if (!TunnelStatus.LISTENSERIALFAIL.equals(getTunnelStatus())) {
      setTunnelStatus(TunnelStatus.LISTENSERIALSUCCESS);
    }
    return this;
  }

  @Override
  public void getDataFromProtocol() throws DataExchangeException {

  }


}
