package com.jiayue.ipfcst.dataexchange.tunnelworker.workassist.iec104tcp;

import com.jiayue.ipfcst.common.data.entity.ProtocolGatherDataPoint;
import com.jiayue.ipfcst.dataexchange.container.ProtocolDataContainer;
import org.joda.time.DateTime;
import wei.yigulu.iec104.annotation.AsduType;
import wei.yigulu.iec104.apdumodel.Apdu;
import wei.yigulu.iec104.asdudataframe.BooleanType;
import wei.yigulu.iec104.asdudataframe.typemodel.IeBoolean;
import wei.yigulu.iec104.asdudataframe.typemodel.InformationBodyAddress;
import wei.yigulu.iec104.nettyconfig.Iec104HSMasterBuilder;
import wei.yigulu.netty.BaseProtocolBuilder;

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

/**
 * 遥信处理
 *
 * @author 修唯xiuwei
 * @version 3.0
 */
@AsduType(typeId = 1)
public class HandelBoolean extends BooleanType {


  private ProtocolDataContainer protocolDataContainer = ProtocolDataContainer.getInstance();

  /**
   * 处理短浮点数据
   *
   * @param apdu 传入的包文
   * @return 返回 响应
   */
  @Override
  public byte[][] handleAndAnswer(Apdu apdu) {
    apdu.getLog().trace("----------处理遥信数据---------");
    BaseProtocolBuilder builder = apdu.getIec104Builder();
    if (builder != null && builder instanceof Iec104HSMasterBuilder) {
      Map<Integer, ProtocolGatherDataPoint> dataPoint = (Map<Integer, ProtocolGatherDataPoint>) builder.getConfigInfoMap().get("104DataPoint");
      builder.getConfigInfoMap().put("lastReceiveTime", DateTime.now());
      HandelBoolean handelBoolean = (HandelBoolean) apdu.getAsdu().getDataFrame();
      List<InformationBodyAddress> address = handelBoolean.getAddresses();
      List<IeBoolean> datas = handelBoolean.getDatas();
      int i = 0;
      //存入共享服务端
      if (apdu.getAsdu().getVsq().getSq() == 0) {
        apdu.getLog().trace("------处理遥信单一寻址-----");
        for (IeBoolean e : datas) {
          if (dataPoint.containsKey(address.get(i).getAddress())) {
            protocolDataContainer.putBoolean(dataPoint.get(address.get(i).getAddress()).getId(), e.isOn());
          }
          i++;
        }
      } else if (apdu.getAsdu().getVsq().getSq() == 1) {
        apdu.getLog().trace("------处理遥信连续寻址-----");
        i = address.get(0).getAddress();
        for (IeBoolean e : datas) {
          if (dataPoint.containsKey(i)) {
            protocolDataContainer.putBoolean(dataPoint.get(i).getId(), e.isOn());
          }
          i++;
        }
      }
    }
    return null;
  }

}
