package com.example;

import android.R.layout;
import android.R.string;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.app.ListActivity;
import android.app.Service;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import android.os.IBinder;
import javax.security.auth.PrivateCredentialPermission;
import android.content.IntentFilter;
import com.example.R;
import android.content.BroadcastReceiver;






@SuppressLint("InflateParams")
public class MainActivity extends Activity {
	
	 private Handler mHandler;
	 private boolean mScanning;
	 private int scanflag=0;
	 private int servicesflag=0;
private int num=0;

private ArrayAdapter<String> arr_adapter;
	private BluetoothAdapter mBluetoothAdapter;
    private ArrayList<BluetoothDevice> mLeDevices;
    private BluetoothDevice mdevice;
    private BluetoothGatt mBluetoothGatt;
   private BluetoothGattCharacteristic characteristic;
	private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
            new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
  
	byte[] WriteBytes = new byte[20];
	
	protected static final int REQUEST_ENABLE_BT = 0;
	private static final long SCAN_PERIOD = 10000;
	 private static final int STATE_CONNECTED = 2;
	 private static final int STATE_DISCONNECTED = 0;
	private int mConnectionState = STATE_DISCONNECTED;
	 private final String LIST_NAME = "NAME";
	 private final String LIST_UUID = "UUID";
	 
	 public final static String fuck1="finded";
	 
	 public final static String fuck2="gatted";
	 
	 public final static String fuck3="charaed";
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	
//getActionBar().setTitle("BLE");
		

mHandler = new Handler();
mLeDevices = new ArrayList<BluetoothDevice>();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    
    finish();
}

final BluetoothManager bluetoothManager =(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

mBluetoothAdapter = bluetoothManager.getAdapter();

mBluetoothAdapter.enable();

setContentView(R.layout.activity_main);



ImageButton button1=null;
button1=(ImageButton) findViewById(R.id.Button1);
	button1.setOnClickListener(myOnClickListener1);
	button1.setClickable(false);
	button1.setBackgroundColor(0xC1C1C1);
	
	ImageButton  button2=null;
button2=(ImageButton ) findViewById(R.id.button2);
button2.setOnClickListener(myOnClickListener2);
button2.setClickable(false);
button2.setBackgroundColor(0xc1c1c1);


ImageButton  button3=null;
button3=(ImageButton ) findViewById(R.id.button3);
button3.setOnClickListener(myOnClickListener3);
button3.setClickable(false);
button3.setBackgroundColor(0xC1C1C1);

ImageButton  button4=null;
button4=(ImageButton ) findViewById(R.id.button4);
button4.setOnClickListener(myOnClickListener4);
button4.setClickable(false);
button4.setBackgroundColor(0xC1C1C1);

Button button0=null;
button0=(Button) findViewById(R.id.button1);
button0.setOnClickListener(myOnClickListener8);

ImageButton button5=null;
button5=(ImageButton) findViewById(R.id.Button5);
button5.setOnClickListener(myOnClickListener5);
button5.setClickable(false);

Button button6=null;
button6=(Button) findViewById(R.id.button6);
button6.setOnClickListener(myOnClickListener6);
button6.setClickable(false);
button6.setBackgroundColor(0xffff3300);

Button button7=null;
button7=(Button) findViewById(R.id.button7);
button7.setOnClickListener(myOnClickListener7);
button7.setClickable(false);
button7.setBackgroundColor(0xf3300);


	}
	


	@Override
	protected void onStart() {
		super.onStart();
	
	scanble(true); 	
	

	// Toast.makeText(MainActivity.this, mdevice.getName(), Toast.LENGTH_SHORT).show();
	//mBluetoothGatt =mdevice.connectGatt(this, false, mGattCallback);

	}


	
	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(mReceiver, makeGattUpdateIntentFilter());
			
	
	 	
	}
	
	  @Override
	    protected void onPause() {
	        super.onPause();
	        unregisterReceiver(mReceiver);
	    }

	
	@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;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	private OnClickListener myOnClickListener1 = new View.OnClickListener() {  
		   
	    public void onClick(View v) {  
	    	
	    	
	    	
	    	 WriteBytes="A".getBytes();
	    	    characteristic.setValue(WriteBytes);
	    		 mBluetoothGatt.writeCharacteristic(characteristic);
	    }
	};
	
	private OnClickListener myOnClickListener2 = new View.OnClickListener() {  
		   
	    public void onClick(View v) {  
	    	
	    	 WriteBytes="B".getBytes();
	    	    characteristic.setValue(WriteBytes);
	    		 mBluetoothGatt.writeCharacteristic(characteristic);
	    }
	};

	private OnClickListener myOnClickListener3 = new View.OnClickListener() {  
		   
	    public void onClick(View v) {  

	    	 WriteBytes="C".getBytes();
	    	    characteristic.setValue(WriteBytes);
	    		 mBluetoothGatt.writeCharacteristic(characteristic);
	    	
	    }
	};
	private OnClickListener myOnClickListener4 = new View.OnClickListener() {  
		   
	    public void onClick(View v) { 
	    	
	    	 WriteBytes="D".getBytes();
	    	    characteristic.setValue(WriteBytes);
	    		 mBluetoothGatt.writeCharacteristic(characteristic);
	    }
	};
	
	private OnClickListener myOnClickListener7= new View.OnClickListener() {  
		   
	    public void onClick(View v) { 
	    	
	    	 WriteBytes="S".getBytes();
	    	    characteristic.setValue(WriteBytes);
	    		 mBluetoothGatt.writeCharacteristic(characteristic);
	    }
	};
	
	private OnClickListener myOnClickListener5= new View.OnClickListener() {  
		
		   
	    public void onClick(View v) { 
	    
	    	 
	   
	    	if(mLeDevices.isEmpty()) Toast.makeText(MainActivity.this, "fuck", Toast.LENGTH_SHORT).show();
	    
	    	else
	    	{ 
	    		
	   
	  
	   // for(int i=0;i<mLeDevices.size();i++){
	    		
	    //	 mdevice=mLeDevices.get(i);
		    		//Toast.makeText(MainActivity.this, mdevice.getName(), Toast.LENGTH_SHORT).show();
	    	
	
	    		
	    		
	    		
	    //	}
	    	
	   
	 //  mdevice=mLeDevices.get(0);
	    showlist();
    	
	   
	    	
	    
	    	
	
	    		 }
	    
	   
	    	
	    }
	};
	
	private OnClickListener myOnClickListener6 = new View.OnClickListener() {  
		   
	    public void onClick(View v) { 

	    	   List<BluetoothGattService> gattServices= mBluetoothGatt.getServices();
		    	
	    	 
	    	 	if(gattServices.isEmpty()) 
	    	 	{
	    	 		Toast.makeText(MainActivity.this, "Services nuu", Toast.LENGTH_SHORT).show();
	    	 		System.exit(0);
	    	 	}
	    	        String uuid = null;
	    	        String unknownServiceString ="U_services";
	    	        String unknownCharaString = "U_chara";
	    	        ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
	    	        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
	    	                = new ArrayList<ArrayList<HashMap<String, String>>>();
	    	        mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

	    	        // Loops through available GATT Services.
	    	      //  Toast.makeText(MainActivity.this, "X", Toast.LENGTH_SHORT).show();
	    	
	    	        for (BluetoothGattService gattService : gattServices) {
	    	            HashMap<String, String> currentServiceData = new HashMap<String, String>();
	    	            uuid = gattService.getUuid().toString();
	    	            currentServiceData.put(
	    	                    LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
	    	            currentServiceData.put(LIST_UUID, uuid);
	    	            gattServiceData.add(currentServiceData);

	    	            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
	    	                    new ArrayList<HashMap<String, String>>();
	    	            List<BluetoothGattCharacteristic> gattCharacteristics =
	    	                    gattService.getCharacteristics();
	    	            ArrayList<BluetoothGattCharacteristic> charas =
	    	                    new ArrayList<BluetoothGattCharacteristic>();

	    	            // Loops through available Characteristics.
	    	            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
	    	                charas.add(gattCharacteristic);
	    	                HashMap<String, String> currentCharaData = new HashMap<String, String>();
	    	                uuid = gattCharacteristic.getUuid().toString();
	    	                currentCharaData.put(
	    	                        LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
	    	                currentCharaData.put(LIST_UUID, uuid);
	    	                gattCharacteristicGroupData.add(currentCharaData);
	    	            }
	    	            mGattCharacteristics.add(charas);
	    	            gattCharacteristicData.add(gattCharacteristicGroupData);
	    	         
	    	        }
	    	 	   
	    	     
	    	 	if( mGattCharacteristics.isEmpty())  {
	    	 		
	    	 		Toast.makeText(MainActivity.this, "chara==NULL", Toast.LENGTH_LONG).show(); 
	    	 		
	    	 	}
	    	 else {
	    		
	    	 	characteristic =mGattCharacteristics.get(0).get(0);
	    	 
	    	 	characteristic.setValue(0,
	    	            BluetoothGattCharacteristic.FORMAT_UINT8, 0); 
	    	 	 String intentAction;
	    	 		intentAction=fuck3;
        	 broadcastUpdate(intentAction);
	    	 	
		    		    		}
		    		    		
		    		    	
	    }
	};
	

	
	private OnClickListener myOnClickListener8 = new View.OnClickListener() {  
		   
	    public void onClick(View v) {  

	    	System.exit(0);
	    	
	    }
	};	

	

	


	
	
	

	
	
	 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            final String action = intent.getAction();
	            if (fuck1.equals(action)) {
	        
	            	ImageButton button5=null;
	    	    	button5=(ImageButton) findViewById(R.id.Button5);
	    	    	button5.setClickable(true);
	            	
	            } 
	            
	            if (fuck2.equals(action)) {
	           
	            	Button button6=null;
	    	    	button6=(Button) findViewById(R.id.button6);
	    	    	button6.setClickable(true);
	    	    	button6.setBackgroundColor(0xff99ff00);
	            	
	            } 
	            if (fuck3.equals(action)) {
	           
	            	ImageButton button1=null;
	    	    	button1=(ImageButton) findViewById(R.id.Button1);
	    	    	button1.setClickable(true);
	    	    	button1.setBackgroundResource(R.drawable.up38ed);
	            	ImageButton button2=null;
	    	    	button2=(ImageButton) findViewById(R.id.button2);
	    	    	button2.setClickable(true);
	    	    	button2.setBackgroundResource(R.drawable.downed);
	            	ImageButton button3=null;
	    	    	button3=(ImageButton) findViewById(R.id.button3);
	    	    	button3.setClickable(true);
	    	    	button3.setBackgroundResource(R.drawable.lefted);
	            	ImageButton button4=null;
	    	    	button4=(ImageButton) findViewById(R.id.button4);
	    	    	button4.setClickable(true);
	    	    	button4.setBackgroundResource(R.drawable.righted);
	    	    	Button button7=null;
	    	    	button7=(Button) findViewById(R.id.button7);
	    	    	button7.setClickable(true);
	    	    	button7.setBackgroundColor(0xffff3300);
	            	
	            } 
	        }
	    };
	    
		
	
	    
	    private void fuckgatt(){
	    
	    	mBluetoothGatt=mdevice.connectGatt(this, false, mGattCallback);
	    }
	    
	    private void showlist(){
	    	
	    	ListView list=null;
	    	list = (ListView)findViewById(R.id.list);
	    	
	    	ArrayList List = new ArrayList();
	    	
	    	int num=mLeDevices.size();
	    	
	    	for(int i=0;i<num;i++){
	    		
	    		List.add(mLeDevices.get(i).getName());
	    	}
	    	
	    	
	    	//String [] arr_data={mLeDevices.get(0).getName(),mLeDevices.get(1).getName()};
	    	
	    	arr_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,List);
	    	list.setAdapter(arr_adapter);
	    	list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
	    	    @Override
	    	    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,   
	                    long arg3) {   
	    	    	
	    	    	mdevice=mLeDevices.get(arg2);
	    	    	Toast.makeText(MainActivity.this, "U choose "+mdevice.getName()+" as receiver", Toast.LENGTH_SHORT).show();
	    	    
	    		
	    		
	    			 fuckgatt();	
	    		}
	    		});
	    	
	    
	    		    
	    	
	    }
	    
	private void scanble(final boolean enable){
	
			if (enable) {
			
	            // Stops scanning after a pre-defined scan period.
	            mHandler.postDelayed(new Runnable() {
	            	
	                @Override
	                public void run() {
	               	 
	       			
	                    mScanning = false;
	                    
	                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
	                    
	                   
	                }
	            }, SCAN_PERIOD);
	           
	            mScanning = true;
	            mBluetoothAdapter.startLeScan(mLeScanCallback);  
	        } else {
	        	 System.exit(0);
	            mScanning = false;
	            mBluetoothAdapter.stopLeScan(mLeScanCallback);
	        }

	}
	
	
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                	
       
                	mLeDevices.add(device);
                	
                	
                }
            });
         if(!mLeDevices.isEmpty()) {
        	 
        	 String intentAction;
     		intentAction=fuck1;
        	 broadcastUpdate(intentAction);
         }
        }
    };

    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
              
                mConnectionState = STATE_CONNECTED;
                
            	intentAction=fuck2;
             	 broadcastUpdate(intentAction);
                
                // Attempts to discover services after successful connection.
                mBluetoothGatt.discoverServices();
             
           	
       	
            
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
              
                mConnectionState = STATE_DISCONNECTED;
              
             //  System.exit(0);
            }
            

        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        	
            if (status == BluetoothGatt.GATT_SUCCESS) {
            	
            	//  System.exit(0);
            /*
            	 String intentAction;
          		intentAction=fuck2;
             	 broadcastUpdate(intentAction);
            */
            }
        }
        
    };
    
    private void broadcastUpdate(final String action) {
    	
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
      
    }
    
    
    private static class SampleGattAttributes {
        private static HashMap<String, String> attributes= new HashMap();
        public static String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";
        public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";

   static{
            // Sample Services.
            attributes.put("0000180d-0000-1000-8000-00805f9b34fb", "Heart Rate Service");
            attributes.put("0000180a-0000-1000-8000-00805f9b34fb", "Device Information Service");
            // Sample Characteristics.
            attributes.put(HEART_RATE_MEASUREMENT, "Heart Rate Measurement");
            attributes.put("00002a29-0000-1000-8000-00805f9b34fb", "Manufacturer Name String");
   }

        public static String lookup(String uuid, String defaultName) {
            String name = attributes.get(uuid);
            return name == null ? defaultName : name;
        }
    }
    
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
       
        intentFilter.addAction(fuck2);
        intentFilter.addAction(fuck1);
        intentFilter.addAction(fuck3);
        return intentFilter;
    }
	
}
