package com.imdroid.beidou_fwd.task;

import com.imdroid.beidou_fwd.entity.XFZData;
import com.imdroid.beidou_fwd.service.TCPClient;
import com.imdroid.beidou_fwd.service.TCPListener;
import com.imdroid.common.util.GsonUtil;
import com.imdroid.common.util.NumberUtils;
import com.imdroid.secapi.dto.GnssCalcData;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class GXXfzForwarder extends Forwarder{
    TCPClient xfzTcpClient;

    class XFZTCPListener implements TCPListener{
        public static final int STATE_NO_ACK = 0;
        public static final int STATE_OK = 1;
        public static final int STATE_FAILED = 2;
        public int state = STATE_NO_ACK;

        public void clear(){
            state = STATE_NO_ACK;
        }
        @Override
        public void onConnected() {

        }

        @Override
        public void onDisconnect() {

        }

        @Override
        public void onMessage(String msg) {
            logger.info("{} client rx: {}",fwdGroupId, msg);
            if(msg.contains("succeed")) state = STATE_OK;
            else state = STATE_FAILED;
        }
    }
    XFZTCPListener listener = new XFZTCPListener();

    @Override
    int send(String projectId, List<GnssCalcData> records, LocalDateTime sentTime){
        int batchNum = 0;
        int sendNum = 0;
        if(records.size() == 0) return 0;

        XFZData xfzTcpMessage = new XFZData();
        xfzTcpMessage.setProjectID(projectId);
        xfzTcpMessage.setWorkPointID(projectId);

        List<XFZData.Data> dataList = new ArrayList<>(records.size());
        xfzTcpMessage.setData(dataList);

        for(GnssCalcData locationRecord: records) {
            XFZData.Data data = new XFZData.Data();
            dataList.add(data);
            data.setDataTime(locationRecord.getCreatetime().format(formatter));
            data.setDevNum(locationRecord.getDeviceid());
            data.setDevtype("GNSS");
            // 单位由mm转化为m
            data.setX(NumberUtils.scale(locationRecord.getRpose() * 0.001, 5));
            data.setY(NumberUtils.scale(locationRecord.getRposn() * 0.001, 5));
            data.setZ(NumberUtils.scale(locationRecord.getRposd() * 0.001, 5));
            // 经纬度
            data.setDevLng(locationRecord.getR9250e());
            data.setDevLat(locationRecord.getR9250n());
/*
            //倾角
            XFZData.Data data2 = new XFZData.Data();
            dataList.add(data2);
            data2.setDataTime(locationRecord.getCreatetime().format(formatter));
            data2.setDevNum(locationRecord.getDeviceid());
            data2.setDevtype("InclinoMeter");
            // 角度
            data2.setX(NumberUtils.scale(locationRecord.getAuxe(), 3));
            data2.setY(NumberUtils.scale(locationRecord.getAuxn(), 3));
            data2.setZ(NumberUtils.scale(locationRecord.getAuxd(), 3));
            // 经纬度
            data2.setDevLng(locationRecord.getR9250e());
            data2.setDevLat(locationRecord.getR9250n());
*/
            // 发送
            batchNum++;

            if(batchNum==20){
                String json = "#" + GsonUtil.toJson(xfzTcpMessage) + "!";
                //logger.debug("project {}: forwad {} gnss records to {}",projectId, dataList.size(),fwdGroupId);
                //logger.debug(json);
                try {
                    listener.clear();
                    xfzTcpClient.writeAndFlush(json);
                    //等待应答
                    if(checkResult()) sendNum += batchNum;
                } catch (Exception e1) {
                    logger.error(e1.toString());
                }
                batchNum = 0;
                dataList.clear();
            }

        }

        if(batchNum>0){
            String json = "#" + GsonUtil.toJson(xfzTcpMessage) + "!";
            logger.debug("project {}: forwad {} gnss records to {}",projectId, dataList.size(),fwdGroupId);
            logger.debug(json);
            try {
                listener.clear();
                xfzTcpClient.writeAndFlush(json);
                //等待应答
                if(checkResult()) sendNum += batchNum;
            } catch (Exception e1) {
                logger.error(e1.toString());
            }
            dataList.clear();
        }
        return sendNum;
    }

    boolean checkResult() throws InterruptedException {
        // 等待应答，最多等500ms
        for(int i=0; i<10; i++){
            Thread.sleep(50);
            if(listener.state == XFZTCPListener.STATE_OK) return true;
            else if(listener.state == XFZTCPListener.STATE_FAILED) return false;
        }
        return false;
    }

}
