package me.aflak.bluetoothterminal;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.util.ArrayList;

import me.aflak.bluetooth.Bluetooth;

public class Chat extends AppCompatActivity implements Bluetooth.CommunicationCallback {
    private String name;
    private Bluetooth b;

    private boolean registered=false;


    //Liste des capteurs disponibles
    private ArrayList<Capteur> capteurs;

    private ArrayList<Boolean> actifs;

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

        actifs = new ArrayList<Boolean>();

        b = new Bluetooth(this);
        b.enableBluetooth();

        b.setCommunicationCallback(this);

        int pos = getIntent().getExtras().getInt("pos");
        name = b.getPairedDevices().get(pos).getName();

        b.connectToDevice(b.getPairedDevices().get(pos));

        //Récupération des capteurs
        capteurs = new ArrayList<Capteur>();
        Bundle extra = getIntent().getExtras();
        for(String s : extra.getStringArrayList("capteurs")) {
            Capteur c = new Capteur(s);
            capteurs.add(c);
            addCaptor(c);
        }


        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mReceiver, filter);
        registered=true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(registered) {
            unregisterReceiver(mReceiver);
            registered=false;

            for(int i = 0; i < actifs.size(); i++)
                if(actifs.get(i))
                    b.send(""+i);

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }

    //Ajout d'un capteur a l'écran
    private void addCaptor(final Capteur c) {

        actifs.add(false);

        //Creation de la ligne
        LinearLayout linearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams linearParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams(linearParam);

        linearLayout.setOrientation(LinearLayout.VERTICAL);


        //Creation des informations capteurs
        TextView textView = new TextView(this);
        textView.setText(c.getNumero() + " : " +c.getType());

        //Creation du bouton on/ff
        Button button = new Button(this);
        button.setText("on/off");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = ""+c.getNumero();

                actifs.set(c.getNumero(), !actifs.get(c.getNumero()));

                if(connect) b.send(msg);

            }
        });

        //Creation de la courbe
        LineChart chart = new LineChart(this);

        ArrayList<Entry> le = new ArrayList<Entry>();
        le.add(new Entry(0, c.getValAct()));

        LineDataSet dataS = new LineDataSet(le, "Valeur");

        LineData ld = new LineData(dataS);

        chart.setLayoutParams(new LinearLayout.LayoutParams(400, 500));

        chart.getXAxis().setDrawLabels(false);

        chart.setData(ld);
        chart.invalidate();

        TextView line = new TextView(this);
        line.setText("______________________________________________");


        linearLayout.addView(textView);
        linearLayout.addView(chart);
        linearLayout.addView(button);
        linearLayout.addView(line);

        LinearLayout lll = (LinearLayout) findViewById(R.id.lll);
        lll.addView(linearLayout);


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.close:
                b.removeCommunicationCallback();
                b.disconnect();
                Intent intent = new Intent(this, Select.class);
                startActivity(intent);
                finish();
                return true;

            case R.id.rate:
                Uri uri = Uri.parse("market://details?id=" + this.getPackageName());
                Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                try {
                    startActivity(goToMarket);
                } catch (ActivityNotFoundException e) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/apps/details?id=" + this.getPackageName())));
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void Display(final String s){
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // traitement de la reception et affichage
                if(connect && s.contains(":")) traitement(s);

            }

            private void traitement (String s) {
                String part1 = s.substring(0, s.indexOf(":"));
                String part2 = s.substring(s.indexOf(":")+1);

                //Permet de récupérer le numéro du capteur (permet également de traiter plus de 10 capteurs)
                int captNumber = Integer.parseInt(part1);
                int valCapt = Integer.parseInt(part2);

                for(Capteur c : capteurs) {
                    if(c.getNumero() == captNumber) {
                        c.setValAct(valCapt);
                    }
                }

                //MISE A JOUR DE L'AFFICHAGE
                LinearLayout layout = (LinearLayout) findViewById(R.id.lll);
                LinearLayout affichage = (LinearLayout)layout.getChildAt(captNumber);
                LineChart chart = (LineChart) affichage.getChildAt(1);
                LineData ld = chart.getLineData();
                Entry e = new Entry(ld.getXMax()+1, valCapt);
                ld.addEntry(e, 0);

                if(ld.getEntryCount() > 100)
                    ld.removeEntry(ld.getDataSets().get(0).getEntryForIndex(0),0);

                chart.setData(ld);
                chart.invalidate();
            }

        });
    }

    boolean connect = false;


    @Override
    public void onConnect(BluetoothDevice device) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                connect = true;

                b.send(getIntent().getExtras().getString("timer"));
            }
        });
    }

    @Override
    public void onDisconnect(BluetoothDevice device, String message) {
        b.connectToDevice(device);
    }

    @Override
    public void onMessage(String message) {
        Display(message);
    }

    @Override
    public void onError(String message) {
        Display("Error: "+message);
    }

    @Override
    public void onConnectError(final BluetoothDevice device, String message) {
        Display("Error: "+message);
        Display("Trying again in 3 sec.");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        b.connectToDevice(device);
                    }
                }, 2000);
            }
        });
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                Intent intent1 = new Intent(Chat.this, Select.class);

                switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        if(registered) {
                            unregisterReceiver(mReceiver);
                            registered=false;
                        }
                        startActivity(intent1);
                        finish();
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        if(registered) {
                            unregisterReceiver(mReceiver);
                            registered=false;
                        }
                        startActivity(intent1);
                        finish();
                        break;
                }
            }
        }
    };
}
