package com.teamltt.carcare.adapter.simulator;

import android.os.Debug;
import android.util.Log;

import com.teamltt.carcare.adapter.IObdSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Jack on 1/25/2017.
 */

public class SimulatedSocket implements IObdSocket {

    private boolean connected = false;
    CountDownLatch latch;
    private byte[] buffer;
    private int numRead;

    public SimulatedSocket() {
        connected = true;
    }

    @Override
    public void connect() throws IOException {

    }

    @Override
    public InputStream getInputStream() throws IOException {
        return null;
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return null;
    }

    @Override
    public boolean isConnected() {
        return connected;
    }

    @Override
    public void close() throws IOException {
        // Noop, because we never really open a socket
        return;
    }

    @Override
    public void writeTo(byte[] bytes) throws IOException {
        if (buffer == null) {
            // todo null check on buffer
            // it sometimes is null when android studio does an Instant Run, but why?
            return;
        }
        String request = new String(bytes);
        if(request.equals("ATZ\r")) {
            String testResponseString = "read";
            byte[] testResponse = testResponseString.getBytes();
            numRead = testResponse.length;
            for(int i = 0; i < numRead; i++) {
                buffer[i] = testResponse[i];
            }
            Log.i("debug Sim", "sending request to sim");
            latch.countDown();
        } else {
            // nothing
        }
    }

    @Override
    public int readFrom(byte[] buffer) throws IOException {
        this.buffer = buffer;
        latch = new CountDownLatch(1);
        try {
            latch.await();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return numRead;

    }
}

@@ -1308,94 +1308,9 @@
   %7D%0A
-        String request = new String(bytes);%0A        if(request.equals(%22ATZ%5Cr%22)) %7B%0A    
+%0A
     
@@ -1350,15 +1350,13 @@
 read
+%5Cn
 %22;%0A
-    
     
@@ -1420,20 +1420,16 @@
         
-   
- 
 numRead 
@@ -1451,20 +1451,16 @@
 length;%0A
-    
         
@@ -1506,20 +1506,16 @@
         
-    
 buffer%5Bi
@@ -1539,34 +1539,26 @@
 i%5D;%0A        
- 
-   %7D%0A    
+%7D%0A
         Log.
@@ -1603,28 +1603,24 @@
 %22);%0A        
-    
 latch.countD
@@ -1630,58 +1630,8 @@
 ();%0A
-        %7D else %7B%0A            // nothing%0A        %7D%0A
     

Generalize simulated socket.