package com.example.wireless;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Scanner;

import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;

public class ConnectedThread extends Thread{
	private InputStream instream;
	private OutputStream outstream;
	private BluetoothSocket mmSocket;
	boolean flag = false;
	public double meg = 4;
	public ConnectedThread(BluetoothSocket socket, boolean f)
	{
		mmSocket = socket;
		InputStream instreamTemp = null;
        OutputStream outstreamTemp = null;
        flag = f;
        try {
        	instreamTemp = socket.getInputStream();
        	outstreamTemp = socket.getOutputStream();
        } catch (IOException e) { Log.d("TRANSFER", e.toString());}
        instream = instreamTemp;
        outstream = outstreamTemp;
	}
	public void run()
	{
		Log.d("TRANSFER", "ConnectedThread running");
		
    	if (flag)
    	{
    		bLife();
    		double startTime = System.nanoTime();
    		//double s = getBatteryLife();
    		write();
    		double endTime = System.nanoTime();
    		double duration = endTime - startTime;
            duration = duration/1000000000.0;
            //double e = getBatteryLife();
            //writeToFile(String.valueOf(duration)+"0.5","20.0mbWriteV2.1");
            //Log.d("TRANSFER", "Battery used :"+(e-s)+"units");
            Log.d("TRANSFER", "Finish writing, took :"+(duration)+"secs.");
            bLife();
    	}
    	else
    	{
    		//double s = getBatteryLife();

    		read();
    		//double e = getBatteryLife();
    		//Log.d("TRANSFER", "Battery used :"+(e-s)+"units");
    	}
    	/*
		double startTime = System.nanoTime();
		double endTime = System.nanoTime();
		while ((endTime-startTime)/1000000000.0<20)
		{
			endTime = System.nanoTime();
		}
		Log.d("TRANSFER", "Everything Done!");*/
	}
	public void write()
	{
		Log.d("TRANSFER", "Write to OutputStream started");
		int f = 8;
		String msg = "";
		byte[] byteString = msg.getBytes();
		int n = (int)(256*meg)*f;
		for (int i=0;i<n;i++)
		{
			msg = msg+"0";
		}//Inner loop
		
		byteString = msg.getBytes();
		for (int j=0;j<1024/8;j++)
		{
			try{
		    	outstream.write(byteString);
		   }
		    	catch (IOException e){Log.d("TRANSFER", e.toString());}
		
		
		}//outer loop
		/*for (int i=0;i<n-1;i++)
		{
			byteString[i]=2;
		}
		byteString[n-1]=1;//Terminating block
		try{
	    	outstream.write(byteString);
	   }
	    	catch (IOException e){Log.d("TRANSFER", e.toString());}*/
		Log.d("TRANSFER", "Write to OutputStream finished");
	}
	public void read()
	{
		bLife();
		double startTime = System.nanoTime();
		double endTime = System.nanoTime();
		//while ((endTime-startTime)/1000000000.0<10)
		//{
			//endTime = System.nanoTime();
		//}
		//startTime = System.nanoTime();
		int bufferSize = 1024*8;
		int totalBytes = 0;
		//boolean ter = false;
		byte[] buffer = new byte[bufferSize];
		//byte[] bufferTer = new byte[bufferSize];
		//for (int i=0;i<bufferSize-1;i++)
		//{
			//bufferTer[i]=0;
		//}
		//bufferTer[bufferSize-1]=1;//Terminating block
		int bytesRead=0;
		while (true) {
			try
			{
			bytesRead = instream.read(buffer);
			totalBytes+=bytesRead;
			//if (buffer[bytesRead-1]==1)
				//break;
			//Log.d("TRANSFER", "BytesRead (while loop) :"+bytesRead);
			/*for (int i=0;i<bytesRead-1;i++)
			{
				if (buffer[i]==2)
					ter = true;
			}
			if (buffer[bytesRead-1]!=1)
				ter = false;
			if (ter)
				break;*/
			if (totalBytes>=1024*1024*1)		
				break;
			}
			catch (Exception e) {
            	Log.d("TRANSFER", e.toString());break;}
            /*try {
                //Read from the InputStream
            	if (totalBytes>=1024000)
            		break;
                bytesRead = instream.read(buffer);
                totalBytes+=bytesRead;
                String result = new String(buffer);
                //Log.d("TRANSFER", "Recieved Message : "+result);
                Log.d("TRANSFER", "BytesRead (outside):"+bytesRead);
                if (bytesRead!=-1)
            	{
            		while ((bytesRead== bufferSize) && (buffer[bufferSize-1]!=1))
            		{
            			result = result + new String(buffer,0,bytesRead);
            			bytesRead = instream.read(buffer);
            			totalBytes+=bytesRead;
            			Log.d("TRANSFER", "BytesRead (while loop) :"+bytesRead);
            		}
            		result = result + new String(buffer,0,bytesRead);
            		//Log.d("TRANSFER", "Recieved Message : "+result);
            		//break;
            	}
            } catch (Exception e) {
            	Log.d("TRANSFER", e.toString());
                break;
            }*/
            
        }
		endTime = System.nanoTime();
        double duration = endTime - startTime;
        duration = duration/1000000000.0;
		Log.d("TRANSFER", "Finish reading, took :"+(duration)+"secs.");
		Log.d("TRANSFER", "Total Bytes read :"+totalBytes);
		Log.d("TRANSFER", "Data transfer speed :"+(totalBytes/duration)+" bytes per second!");
		bLife();
		//writeToFile(String.valueOf(totalBytes)+","+String.valueOf(duration),"TerminatingBlock2MBBluetooth3S2Tab.txt");
		
		
	}
	public void writeToFile(String text, String fileName)
	{
		try {
			File pPath= Environment.getExternalStorageDirectory();
			boolean bReturn= pPath.mkdirs();
			File pFile= new File(pPath, fileName);
	        pFile.createNewFile();
			FileOutputStream fOut = new FileOutputStream(pFile);
			OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);;
			myOutWriter.append(text);
			myOutWriter.close();
			fOut.close();
			Log.d("TRANSFER", "Done writing to text file!");
		}
		catch (Exception e){Log.d("TRANSFER", e.toString());}
	}
	public void write(byte[] bytes) {
        try {
            outstream.write(bytes);
        } catch (IOException e) { Log.d("TRANSFER", e.toString());}
    }
	public double getBatteryLife()
	{
		IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = MyApplication.getAppContext().registerReceiver(null, ifilter);
        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        double bat = level/ (float)scale;
        Log.d("TRANSFER", "Battery level:"+bat);
        return bat;
	
	}
	public void bLife() {
        BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
            int scale = -1;
             int level = -1;
            int voltage = -1;
            int temp = -1;
            @Override
            public void onReceive(Context context, Intent intent) {
                level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
                voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
                Log.d("TRANSFER", "level is "+level+"/"+scale+", temp is "+temp+", voltage is "+voltage);
            }
        };
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
       //s registerReceiver(batteryReceiver, filter);
    }
}
