

package bluetooth.uhura;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import bluetooth.uhura.BluetoothSerialComm;
import hr.fer.labust.seatrac.SeatracFactory;
import hr.fer.labust.seatrac.SeatracFactoryCoder;
import hr.fer.labust.seatrac.SeatracMessage;
import hr.fer.labust.seatrac.datatypes.AcoFix;
import hr.fer.labust.seatrac.datatypes.BitMessageTest;
import hr.fer.labust.seatrac.messages.responses.PingResp;
import hr.fer.labust.util.HexConverter;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.app.ListActivity;
import android.widget.Toast;

import com.google.common.io.LittleEndianDataInputStream;
import com.google.common.io.LittleEndianDataOutputStream;


public class MainActivity extends Activity {

	private Button On,Off,Visible,list,list2,Send,Send2,Connect,Connect2;
	private EditText inp,inp2;
	private ListView lv,lv2;
	private BluetoothSerialComm BSC=new BluetoothSerialComm();
	private BluetoothAdapter BA;
	private Set<BluetoothDevice>pairedDevices;
	private BluetoothDevice selectedDevice, selectedDevice2;
	private TextView logview;
	
	private BluetoothInterface bti = null;
	private BluetoothInterface bti2 = null;

private long lastTime = 0;

final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        String data = msg.getData().getString("receivedData");

        long t = System.currentTimeMillis();
        if(t-lastTime > 100) {
            logview.append("\n");
            lastTime = System.currentTimeMillis();
        }
        logview.append(data);
    }
};

final Handler handlerStatus = new Handler() {
    public void handleMessage(Message msg) {
        int co = msg.arg1;
        if(co == 1) {
            logview.append("Connected\n");
        } else if(co == 2) {
            logview.append("Disconnected\n");
        }
    }
};

/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   On = (Button)findViewById(R.id.button1);
   Off = (Button)findViewById(R.id.button4);
   Visible = (Button)findViewById(R.id.button2);
   list = (Button)findViewById(R.id.button3);
   Send=(Button)findViewById(R.id.button5);
   Connect=(Button)findViewById(R.id.button7);
   lv = (ListView)findViewById(R.id.listView1); //list of paired devices
   //lv2 = (ListView)findViewById(R.id.listView2); //list of rec messages
   inp=(EditText)findViewById(R.id.editText1);
   logview=(TextView)findViewById(R.id.logview);
   
   list2 = (Button)findViewById(R.id.Button01);
   Send2=(Button)findViewById(R.id.Button02);
   Connect2=(Button)findViewById(R.id.Button03);
   lv2 = (ListView)findViewById(R.id.ListView01); //list of paired devices
   inp2=(EditText)findViewById(R.id.EditText01);
   
   selectedDevice=null;
   selectedDevice2=null;
   
   Toast.makeText(getApplicationContext(),"Starting init",Toast.LENGTH_LONG).show();
   
   BSC.init();
   Toast.makeText(getApplicationContext(),"Init done",Toast.LENGTH_LONG).show();

   BA=BSC.getAdapter();
   pairedDevices=BSC.getDevices();
   
   lv.setOnItemClickListener(new OnItemClickListener() {
 		@Override
 		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 			int i=0; String name=null; String adr=null;
 			for(BluetoothDevice bt : pairedDevices){
 		         name=bt.getName();
 		         adr=bt.getAddress();
 		         selectedDevice=bt;
 		         if (id==i) break;
 		         i++;
 			}
 			Toast.makeText(getApplicationContext(),"Device 1: "+name+" "+adr,Toast.LENGTH_LONG).show();
 		//call to make connection with selected device
 		}
   });
 		
 		lv2.setOnItemClickListener(new OnItemClickListener() {
 	 		@Override
 	 		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 	 			int i=0; String name=null; String adr=null;
 	 			for(BluetoothDevice bt : pairedDevices){
 	 		         name=bt.getName();
 	 		         adr=bt.getAddress();
 	 		         selectedDevice2=bt;
 	 		         if (id==i) break;
 	 		         i++;
 	 			}
 	 			Toast.makeText(getApplicationContext(),"Device 2: "+name+" "+adr,Toast.LENGTH_LONG).show();
 	 		//call to make connection with selected device
 	 		}
 	 	});

    seatracTest();
 	

}

    public void onPingResp(PingResp msg)
    {
        logview.append("Source: " + msg.acofix.src + "\n");
        logview.append("RSSI: " + Arrays.toString(msg.acofix.usbl.rssi) + "\n");
        logview.append("Position: " + Arrays.toString(msg.acofix.position) + "\n");
    }

    public void seatracTest() {

        PingResp msg = (PingResp) SeatracFactory.createResponse(PingResp.CID);
        msg.acofix.src = 2;
        msg.acofix.flags.USBL_VALID = 1;
        msg.acofix.flags.POSITION_VALID = 1;
        msg.acofix.usbl.rssi = new short[2];
        msg.acofix.usbl.rssi[0] = 300;
        msg.acofix.usbl.rssi[1] = -1024;
        msg.acofix.position[AcoFix.x] = 513;
        msg.acofix.position[AcoFix.y] = 402;
        msg.acofix.position[AcoFix.z] = 10002;

        try {
            String m = SeatracFactoryCoder.encodeMessage(msg);
            logview.append(m + "\n");

            SeatracMessage msg2 = SeatracFactoryCoder.decodeMessage(m);
            onPingResp((PingResp) msg2);

            BitMessageTest bt = new BitMessageTest();
            bt.lat = 1024;
            bt.lon = 4096;
            bt.type = 1;

            logview.append("Lat:" + bt.lat + "\n");
            logview.append("Lon:" + bt.lon + "\n");
            logview.append("Type:" + bt.type + "\n");

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            LittleEndianDataOutputStream os = new LittleEndianDataOutputStream(out);
            bt.pack(os);

            String data = HexConverter.bytesToHex(out.toByteArray());
            System.out.println(data);

            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
            LittleEndianDataInputStream is = new LittleEndianDataInputStream(in);

            bt.unpack(is);

            logview.append("Lat:" + bt.lat + "\n");
            logview.append("Lon:" + bt.lon + "\n");
            logview.append("Type:" + bt.type + "\n");
        } catch (IOException e) {

        }
    }


public void on(View view){
   if (!BA.isEnabled()) {
      Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(turnOn, 0);
      Toast.makeText(getApplicationContext(),"Turned on",Toast.LENGTH_LONG).show();
   }
   else{
      Toast.makeText(getApplicationContext(),"Already on",Toast.LENGTH_LONG).show();
      }
}
public void list(View view){
   ArrayList list = new ArrayList();
   for(BluetoothDevice bt : pairedDevices)
      list.add(bt.getName());

   Toast.makeText(getApplicationContext(),"Showing Paired Devices",Toast.LENGTH_SHORT).show();
   final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
   lv.setAdapter(adapter);

}
public void list2(View view){
	   ArrayList list2 = new ArrayList();
	   for(BluetoothDevice bt : pairedDevices)
	      list2.add(bt.getName());

	   Toast.makeText(getApplicationContext(),"Showing Paired Devices",Toast.LENGTH_SHORT).show();
	   final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list2);
	   lv2.setAdapter(adapter);

	}
public void off(View view){
   if (BA.isEnabled()) {
 	  BA.disable();
       Toast.makeText(getApplicationContext(),"Turned off",Toast.LENGTH_LONG).show();
    }
    else{
       Toast.makeText(getApplicationContext(),"Already off",Toast.LENGTH_LONG).show();
       }
}
public void visible(View view){
   Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
   startActivityForResult(getVisible, 0);
}

public void send(View view){
	  Toast.makeText(getApplicationContext(),"Sending message to Device 1: "+inp.getText().toString(),Toast.LENGTH_LONG).show();
	  bti.sendData(inp.getText().toString());
 }

public void send2(View view){
	  Toast.makeText(getApplicationContext(),"Sending message to Device 2: "+inp2.getText().toString(),Toast.LENGTH_LONG).show();
	  bti2.sendData(inp2.getText().toString());
}
 public void reqConnect(View view) throws IOException{
	   
	   
	   if(!(selectedDevice==null))
	   {
	   Toast.makeText(getApplicationContext(),"Connecting to "+selectedDevice.getName()+" as Device 1 with MAC address "+selectedDevice.getAddress(),Toast.LENGTH_LONG).show();
	   bti = new BluetoothInterface(selectedDevice, handlerStatus, handler);
	   bti.connect();
	   }
 }
 
 public void reqConnect2(View view) throws IOException{
	   
	   
	   if(!(selectedDevice2==null))
	   {
	   Toast.makeText(getApplicationContext(),"Connecting to "+selectedDevice2.getName()+" as Device 2 with MAC address "+selectedDevice2.getAddress(),Toast.LENGTH_LONG).show();
	   bti2 = new BluetoothInterface(selectedDevice2, handlerStatus, handler);
	   bti2.connect();
	   }
}
	

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   // Inflate the menu; this adds items to the action bar if it is present.
   getMenuInflater().inflate(R.menu.main, menu);
   return true;
}
}

