package com.example.micha.krokomer;

import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {

    private float posledneHodnoty[] = new float[3*2];
    private float poslednySmer[] = new float[3*2];
    private float posledneExtremy[][] = new float[3*2][3*2];
    private float poslednyDif[] = new float[3*2];

    private float limit = 10;
    private float yOdchylka;
    private float vaha;
    private int poslednaZhoda = -1;
    private int kroky = 0;

    private TextView pocetKrokov;
    private TextView senzitivita;
    private SeekBar bar;
    private Button vynulovat;

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

        final View controlsView = findViewById(R.id.fullscreen_content_controls);
        final View contentView = findViewById(R.id.fullscreen_content);
        pocetKrokov = (TextView) findViewById(R.id.textPocetKrokovData);
        senzitivita = (TextView) findViewById(R.id.textcitlivostData);
        senzitivita.setText("35");
        bar = (SeekBar) findViewById(R.id.seekBar1);
        bar.setOnSeekBarChangeListener(this);

        yOdchylka = 240.0f;
        vaha = - (yOdchylka / (SensorManager.MAGNETIC_FIELD_EARTH_MAX));
        vynulovat = (Button) findViewById(R.id.buttonVynulovat);
        vynulovat.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                posledneHodnoty = new float[3*2];
                poslednySmer = new float[3*2];
                posledneExtremy = new float[3*2][3*2];
                poslednyDif= new float[3*2];
                kroky = 0;
                Toast.makeText(getApplicationContext(), "Pocet krokov vynulovany", Toast.LENGTH_SHORT).show();
            }
        });

        SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (sensor == null) {
            new AlertDialog.Builder(this)
                    .setMessage("Chyba senzor akceleracie.")
                    .setCancelable(false)
                    .setPositiveButton("Rozumiem", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            MainActivity.this.finish();
                        }
                    })
                    .show();
        }
        sensorManager.registerListener(new MyListener(), sensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    class MyListener implements SensorEventListener {
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            synchronized (this) {
                float vSum = 0;
                for (int i = 0; i < 3; i++) {
                    final float v = yOdchylka + event.values[i] * vaha;
                    vSum += v;
                }
                int k = 0;
                float v = vSum / 3;
                float direction = (v > posledneHodnoty[k] ? 1
                        : (v < posledneHodnoty[k] ? -1 : 0));
                if (direction == -poslednySmer[k]) {
                    // zmena smeru
                    int typ = (direction > 0 ? 0 : 1); // min alebo max?

                    posledneExtremy[typ][k] = posledneHodnoty[k];
                    float dif = Math.abs(posledneExtremy[typ][k] - posledneExtremy[1 - typ][k]);

                    if (dif > limit) {
                        boolean podobneVelky = dif > (poslednyDif[k] * 2 / 3);
                        boolean predosliDostVelky = poslednyDif[k] > (dif / 3);
                        boolean nieKontra = (poslednaZhoda != 1 - typ);
                        if (podobneVelky && predosliDostVelky
                                && nieKontra) {
                            kroky++;
                            poslednaZhoda = typ;
                        } else {
                            poslednaZhoda = -1; // nebol krok
                        }
                    }
                    poslednyDif[k] = dif;
                }
                poslednySmer[k] = direction;
                posledneHodnoty[k] = v;
            }
            pocetKrokov.setText(String.valueOf(kroky));
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setMessage("Ukoncit aplikaciu?")
                .setCancelable(false)
                .setPositiveButton("Ano", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MainActivity.this.finish();
                    }
                })
                .setNegativeButton("Nie", null)
                .show();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        limit = (float)(bar.getMax() - progress);
        senzitivita.setText(Integer.toString(progress));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }
}
