package org.ts.ddcs.DataItemTemplate;


import org.ts.ddcs.Entity.RtuStatusEntity;
import org.ts.ddcs.Tool.BytesHelp;
import org.ts.ddcs.Tool.StringUtil;

import java.util.LinkedList;
import java.util.List;

/**
 * funcode 0xFF57
 * 上报状态（每一路的上报状态）
 * 连续6组，(1+5),1组总包索引，5组已发索引
 */
@SuppressWarnings("all")
public class DataItemTemplateFF57 extends DataItemTemplate {


    @Override
    public byte[] Stream(byte[] data) {
        byte[] remain = data;
        if (this.macth) {
            return remain;
        }
        int count = 0;
        String flag = BytesHelp.byte2HexStr(remain, count, 2);
        count += 2;
        if (flag.equals(this.feture)) {
            byte[] len = BytesHelp.subBytes(remain, count, 1);
            count += 1;
            int dataTotalLen = len[0] >> 3;
            if (dataTotalLen == 12) {
                byte[] buff = BytesHelp.subBytes(remain, count, dataTotalLen);
                String hexStr = BytesHelp.byte2HexStr(buff);
                this.varcharValue = hexStr;
            }
            count += dataTotalLen;
            remain = BytesHelp.subBytes(remain, count, remain.length - count);
            this.macth = true;
        }
        return remain;
    }

    @Override
    public void SetEntity(Object entity) {
        if (null != this.varcharValue) {
            List<Integer> status = new LinkedList<>();
            byte[] buff = BytesHelp.hexStr2Bytes(this.varcharValue);
            if (null != buff && buff.length ==12){
                for (int i = 0; i < 6; i++) {
                    byte[] valueBuff = BytesHelp.subBytes(buff, i * 2, 2);
                    String hexStr = BytesHelp.byte2HexStr(valueBuff);
                    if (hexStr.equals("FFFF")) {//FFFF代表此路IP无效
                        status.add(new Integer(-1));
                    }else{
                        StringBuffer dataStr = new StringBuffer(hexStr);
                        String value = StringUtil.getPrettyNumber(dataStr.toString());
                        status.add(new Integer(Integer.parseInt(value)));
                    }
                }
            }
            RtuStatusEntity statusEntity = (RtuStatusEntity) entity;
            statusEntity.setSendChancelIndex(status);
        }
    }
}
