package com.fpgalover.fpgalover_usb_serial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

//few android libraries
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

//the USB-serial Libraries
import com.fpgalover.fpgalover_usb_serial.ResponseStatus;
import com.fpgalover.fpgalover_usb_serial.USBSerialConnector;
import com.fpgalover.fpgalover_usb_serial.USBSerialListener;
import com.fpgalover.fpgalover_usb_serial.Utilities;


public class Fpgalover_USB_Serial extends AppCompatActivity implements USBSerialListener {

    USBSerialConnector mConnector;// USB-serial library class
    EditText txTEXT;
    EditText rxTEXT;
    Button btSend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fpgalover__usb__serial);
        mConnector = USBSerialConnector.getInstance();
        txTEXT = (EditText) findViewById(R.id.txText);
        rxTEXT = (EditText) findViewById(R.id.rxText);
        btSend = (Button) findViewById(R.id.btSend);
        txTEXT.setEnabled(false);
        rxTEXT.setEnabled(false);
        btSend.setEnabled(false);

        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String data = txTEXT.getText().toString();
                mConnector.writeAsync(data.getBytes());
            }
        });

    }

    @Override
    public void onDataReceived(byte[] data) {
        if (data != null) {
            rxTEXT.setText(rxTEXT.getText()+"\n HEX>"+Utilities.bytesToHex(data)+"\nSTRING>"+Utilities.bytesToString(data));
        } else {

        }
    }

    @Override
    public void onErrorReceived(String data) {
        Toast.makeText(this, data, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDeviceReady(ResponseStatus responseStatus) {
        txTEXT.setEnabled(true);
        rxTEXT.setEnabled(true);
        btSend.setEnabled(true);
    }

    @Override
    public void onDeviceDisconnected() {
        Toast.makeText(this, "Device disconnected", Toast.LENGTH_LONG).show();
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mConnector.setUsbSerialListener(this);
        mConnector.init(this, 115200);
    }
    @Override
    protected void onPause() {
        super.onPause();
        mConnector.pausedActivity();
    }


}
