package com.tDiagnostics.diagnostics.blocks;

import com.fazecast.jSerialComm.SerialPort;
import com.tDiagnostics.communication.handler.ConnectionHandler;

public class GroupReadingResponse {
    public static int readFirstPackage(SerialPort in, ConnectionHandler con){
        System.out.println("START_readFirstPackage");
        int len = 1;
        byte buf[] = new byte[len];
        if(con.startZeros) {
            in.readBytes(buf, buf.length);
            in.readBytes(buf, buf.length);///mingi kahtlased nullid

            System.out.println("ignored two zeroes");
        }
        in.readBytes(buf, buf.length);
        con.syncbyte = con.bytesToHex(buf);

        System.out.println("syncbyte: " + String.format("0x%02x", con.syncbyte));
        if(con.syncbyte == 0)
            con.startZeros = true;
        if(con.syncbyte != 0x55)
            return 1;

        in.readBytes(buf, buf.length);
        con.LSB = con.bytesToHex(buf);
        System.out.println("LSB: " + String.format("0x%02x", con.LSB));
        if(con.LSB != 0x01)
            return 1;

        in.readBytes(buf, buf.length);
        con.HSB = con.bytesToHex(buf);
        System.out.println("HSB: " + String.format("0x%02x", con.HSB));
        if(con.HSB != 0x8A)
            return 1;

        in.writeBytes(con.toByteArray((0xFF - con.HSB)), len);

        if(!con.echoOn && !con.skipEchoCheck) {
            in.readBytes(buf, buf.length);
            if (con.bytesToHex(buf) == 0xFF - con.HSB) {
                con.echoOn = true;

                return 1;
            }else{
                con.skipEchoCheck = true;
            }

        }else{
            con.cancelEcho(in);
        }

        return 0;

    }
    //
    public static void readECUDataPackage(SerialPort port, ConnectionHandler con){
        System.out.println("START_readECUDataPackage");
        for(;;){
            int dat = con.readByte(port,0, false);
            System.out.println(dat);
            if(dat == 0x03)
                break;
            con.sendByte(port, 0xFF-dat, true);


        }

    }
    public static Integer[][] readSensorDataBlock(SerialPort port, ConnectionHandler con){
        System.out.println("START_readSensorDataBlock");
        Integer blockReadingValues[][] = new Integer[4][3];
        int j = 0, k = 0;
        for(;;){
            int dat = con.readByte(port,0, false);
            if(dat == 0x03)
                break;
            con.sendByte(port, 0xFF-dat, true);

            blockReadingValues[j][k] = dat;
            k++;
            if(k == 3){
                k = 0;
                j++;
            }
        }
        return blockReadingValues;
    }
}