package diploma.eu.cz.karel.smarthome;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

/**
 * @author DolezalK
 */
public class BluetoothService extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{

    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;

    Editable nameb;
    String blname;
    int stat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);

        //////////////////////////////////////////////////////////////// drawer menu /////////////////////////////////////////////////////////
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        //////////////////////////////////////////////////////////////// control bluetooth /////////////////////////////////////////////////////
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) //query for bluetooth available
        {
            Toast.makeText(this, "Device does not bluetooth", Toast.LENGTH_LONG).show(); // notification
            finish();
            return;
        }
        /*
        if (!mBluetoothAdapter.isEnabled())
        {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); //query for run bluetooth
            startActivityForResult(enableIntent, 3); //run dialog window
        }*/

        View v = new View(this); //create view
        final EditText name = (EditText) findViewById(R.id.editText1);
        Button ok = (Button) findViewById(R.id.button1);
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) { // button1 OK

                nameb = name.getText();
                blname = nameb.toString();
                try {
                    findBT(); //connect bluetooth
                    stat = 1; //set 1
                } catch (IOException e) {
                    stat = 0; //set 0
                    e.printStackTrace();
                }
            }
        });

        final Switch light1 = (Switch) findViewById(R.id.bl_swtch_LR_ligth);
        light1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (light1.isChecked()) {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('1');
                        } catch (IOException e) {
                            Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else
                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                } else {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('2');
                        } catch (IOException e) {
                            Toast.makeText(BluetoothService.this,
                                    "Connection not established with your home",
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else

                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                }
            }
        });

        final Switch light2 = (Switch) findViewById(R.id.bl_swtch_LR_lamp);
        light2.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (light2.isChecked()) {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('3');
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else
                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                } else {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('4');
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(BluetoothService.this,
                                    "Connection not established with your home",
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else

                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                }
            }
        });
        final Switch light3 = (Switch) findViewById(R.id.bl_swtch_KCH_light);
        light3.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (light3.isChecked()) {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('5');
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else
                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                } else {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('6');
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(BluetoothService.this,
                                    "Connection not established with your home",
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else

                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                }
            }
        });

        final Switch light4 = (Switch) findViewById(R.id.bl_swtch_KCH_sideboard);
        light4.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (light4.isChecked()) {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('7');
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else
                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                } else {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('8');
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(BluetoothService.this,
                                    "Connection not established with your home",
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else

                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                }
            }
        });

        final Switch light5 = (Switch) findViewById(R.id.bl_swtch_ET_light);
        light5.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (light5.isChecked()) {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('9');
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else
                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                } else {
                    if (stat == 1) {
                        try {
                            mmOutputStream.write('0');
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(BluetoothService.this,
                                    "Connection not established with your home",
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    } else

                        Toast.makeText(BluetoothService.this, "Connection not established with your home", Toast.LENGTH_LONG).show();
                }
            }
        });
    } //end create
/////////////////////////////////////////////////////////////////// connect bluetooth //////////////////////////////////////////////////////////////
    protected void findBT() throws IOException {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 1);
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices) {
                if (device.getName().equals(blname))
                {
                    mmDevice = device;
                    break;
                }
            }
        }
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();
    }

    public void closeConnection() {
        try {

            mmOutputStream.close();
            mmInputStream.close();
            mmSocket.close();

        } catch (IOException ex) {
            ex.printStackTrace();
            Toast.makeText(this, "Error disconnect!!!", Toast.LENGTH_LONG).show();
        }
    }//end closeConnection

    /////////////////////////////////////////////////////////// complet menu ////////////////////////////////////////////////////////////////

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_blue, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_disconnect) {
            closeConnection();
            return true;
        }
        if (id == R.id.action_connect_bluetooth) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            //case R.id.nav_bluetooth:
            case R.id.nav_network:Intent intent = new Intent(this, NetworkService.class);
                startActivity(intent);
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}
