package it.andoma.legocarcontroller;

import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by mling_000 on 11/09/2016.
 */
public class ConnectionManager extends Thread {

    private BluetoothSocket btS;
    private InputStream inputStream;
    private OutputStream outputStream;

    private boolean stop;

    private static ConnectionManager instance = null;

    private float tempSens = 0;

    public static ConnectionManager getInstance() {
        if(instance == null) instance = new ConnectionManager();
        return instance;
    }

    private ConnectionManager() {
        stop = true;
    }

    public void setChannel(BluetoothSocket socket) {
        this.btS = socket;

        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
        } catch(IOException e) {}

        stop = false;
    }

    public void run() {
        byte[] buffer = null;
        String info = "";

        while(!stop) {
            try {
                int bytesAvailable = inputStream.available();
                 if(bytesAvailable > 0) {
                     buffer = new byte[bytesAvailable];
                     inputStream.read(buffer);

                     info += new String(buffer, "US-ASCII");

                     //ascii 10 = line feed
                     if(buffer[buffer.length - 1] == 10) {
                         Log.d("legocar", info);
                         tempSens = Float.valueOf(info);
                         info = "";
                     }
                 }
            } catch (IOException e) {
                break;
            }
        }
    }

    public boolean write(byte[] bytes) {
        if(outputStream == null) return false;

        try {
            outputStream.write(bytes);
        } catch (IOException e) {
            return false;
        }

        Log.d("legocar", "inviato");

        return true;
    }

    public void close() {
        try {
            btS.close();
        } catch (IOException e) {}
    }

    public float getTempSens() {
        return tempSens;
    }

}
