package  org.ts.ddcs.dataprocesser.dtuDatagram;

import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.main.DataProcessHolder;
import org.ts.ddcs.common.constant.GBConstants;
import org.ts.ddcs.dataStream.DataStreamAdapter;
import org.ts.ddcs.dataprocesser.DataProcesser;
import org.ts.ddcs.dataprocesser.DataProcesserInterface;
import org.ts.ddcs.datatemplate.DataTemplateInterface;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.net.DataChannelHolder;
import org.ts.ddcs.util.BytesUtil;


import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * created by swp on 2017/8/28
 *
 * @author dylan
 */

public class DtuLinkDataProcesser extends DataProcesser implements DataProcesserInterface {
    @Override
    public void packetReadly(byte[] byteBuff, int pos, int length, DataStreamAdapter dataStreamAdapter, DataTemplateInterface template) {
        String logId = LogHelper.createLogId("DtuLinkDataProcesser");
        try {
            Date dt = new Date();
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            byte[] datagramBuff = new byte[length];
            System.arraycopy(byteBuff, pos, datagramBuff, 0, length);
            String datagram = BytesUtil.byte2HexStr(datagramBuff);
            LogHelper.info(logId + " datagram :" + datagram);
            String uuid = new String(template.rtuCode(), "UTF-8");
            LogHelper.info(logId + " uuid: " + uuid);
            dataStreamAdapter.setCode(uuid);
            byte[] dataGram = BytesUtil.subBytes(byteBuff, pos, length);
            String gram = BytesUtil.byte2HexStr(dataGram);
            JSONObject body = new JSONObject();
            body.put(GBConstants.BASE_KEY_DATAGRAM, gram);
            body.put(GBConstants.BASE_KEY_RTU, uuid);
            body.put(GBConstants.BASE_KEY_AGREEMENT, template.agreement());
            body.put(GBConstants.BASE_KEY_DATAGRAM_PICK_TM, timeFormat.format(dt));
            body.put("afc",BytesUtil.byte2HexStr(template.funcCode()));
            DataChannelHolder.newInstance().dataChannel.online(dataStreamAdapter);
          //  DataProcessHolder.newInstance().dataProcess.submitRelayDatagramTask(body);
            LogHelper.info(logId + " " + "success pick datagram" + body.toJSONString());
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }
}
