using System;
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Bluetooth;
using Android.Widget;
using FanControllerBluetooth;
using System.Linq;
using AlertDialog = Android.App.AlertDialog;

namespace FanControllerBluetooth
{
    [Activity(Label = "Fan Controller Bluetooth", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : Activity
    {

        BluetoothConnection myConnection = new BluetoothConnection();
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);


            // Get our button from the layout resource,
            // and attach an event to it
            Button buttonConnect = FindViewById<Button>(Resource.Id.button1);
            Button buttonDisconnect = FindViewById<Button>(Resource.Id.button2);

            SeekBar fanDrehzahl = FindViewById<SeekBar>(Resource.Id.seekBar1);

            TextView connected = FindViewById<TextView>(Resource.Id.textView1);



            BluetoothSocket _socket = null;




            buttonConnect.Click += delegate
            {


                myConnection = new BluetoothConnection();
                myConnection.getAdapter();
                myConnection.thisAdapter.StartDiscovery();

                try
                {
                    myConnection.getDevice();
                    myConnection.thisDevice.SetPairingConfirmation(false);

                    myConnection.thisDevice.SetPairingConfirmation(true);
                    myConnection.thisDevice.CreateBond();

                }
                catch (Exception deviceEX)
                {
                }
                myConnection.thisAdapter.CancelDiscovery();

                try
                { _socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")); } //the UUID of HC-05 and HC-06 is the same
                catch (Exception ex)
                {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                    AlertDialog alert = dialog.Create();
                    alert.SetTitle("Error");
                    alert.SetMessage("Please go to settings and connect with the bluetooth module at first.");
                    alert.SetButton("OK", (c, ev) =>
                    {
                        // Ok button click task: alert goes away  
                    });
                    alert.Show();
                }

                myConnection.thisSocket = _socket;

                try
                {
                    myConnection.thisSocket.Connect();

                    connected.Text = "Connected to the Arduino!";
                    buttonDisconnect.Enabled = true;
                    buttonConnect.Enabled = false;

                }
                catch (Exception CloseEX)
                { }
            };

            buttonDisconnect.Click += delegate
            {

                try
                {
                    buttonConnect.Enabled = true;

                    myConnection.thisDevice.Dispose();

                    myConnection.thisSocket.OutputStream.WriteByte(200);
                    myConnection.thisSocket.OutputStream.Close();

                    myConnection.thisSocket.Close();

                    myConnection = new BluetoothConnection();
                    _socket = null;

                    connected.Text = "Not connected to the Arduino!";
                }
                catch { }
            };



            fanDrehzahl.ProgressChanged += (object sender, SeekBar.ProgressChangedEventArgs e) =>
            {
                if (e.FromUser)
                {
                    try
                    {

                        myConnection.thisSocket.OutputStream.WriteByte(Convert.ToByte(e.Progress + 1));
                        System.Threading.Thread.Sleep(10);
                    }
                    catch { }
                }
            };
        }
    }




    public class BluetoothConnection
    {

        public void getAdapter() { this.thisAdapter = BluetoothAdapter.DefaultAdapter; }
        
        
        //change the bd.name according to the name of your bluetooth module
        public void getDevice() { this.thisDevice = (from bd in this.thisAdapter.BondedDevices where bd.Name == "HC-05" select bd).FirstOrDefault(); } 

        public BluetoothAdapter thisAdapter { get; set; }
        public BluetoothDevice thisDevice { get; set; }

        public BluetoothSocket thisSocket { get; set; }
    }
}