package com.example.stimulusStrategy;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.TriggerEvent;
import android.hardware.TriggerEventListener;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.pharmacy.frontEnd.R;
import com.example.stimulus.SedentaryStimulus;

import java.util.Calendar;


/**
 * Created by pharmacy on 09/01/2018.
 */

public class Accelerometer extends Service implements StimulusStrategy, SensorEventListener {

    private SensorManager mSensorManager;
    private AlarmManager am;
   //private Context context;
    private int startId;
    private float[] history = new float[3];
    private int historicMovement = 0;
    private long historyTime;
    private int prevMinutes = 0;
    private int minutes;


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ACCEL", "CREATED ACCEL");
        historyTime = SystemClock.elapsedRealtimeNanos();
        this.startId = startId;
        mSensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 600000000);
        //Sampling period is still far too often here.
        //Parameters to be set here such as delay etc.
        //Slightly better when app is not in foreground
        am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        setUpDailyProgress();
        setUpClock();
        return START_STICKY;
    }

    private void setUpDailyProgress(){
        SharedPreferences sharedPref = this.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
        if(currentDay == sharedPref.getInt(getString(R.string.progress_day), 0)) {
            minutes = sharedPref.getInt(getString(R.string.daily_progress), 0);
        } else {
            minutes = 0;
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt(getString(R.string.progress_day), currentDay);
            editor.putInt(getString(R.string.daily_progress), minutes);
            editor.commit();
        }

        prevMinutes = minutes;
    }

    private void setUpClock() {
        SharedPreferences shared = this.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        Intent i = new Intent(getBaseContext(), com.example.stimulus.SedentaryStimulus.class);
        //i.putExtras(new Intent(this, this.getClass()));
       // i.putExtra(getString(R.string.serviceID), startId);
        PendingIntent pi = PendingIntent.getBroadcast(getBaseContext(), R.integer.alarm_rc, i, PendingIntent.FLAG_UPDATE_CURRENT);
        //test
        //am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+3000, pi);
        int interval = shared.getInt(getString(R.string.daily_goal), getResources().getInteger(R.integer.notify_period_minutes));

        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+(1000*60*interval), pi);
         Log.d("myTag", "ALARM SET" + interval);
    }



    public void monitor() {

        Log.d("ACCEL", "MONITORING");
        Toast saved = Toast.makeText(this, R.string.motion,Toast.LENGTH_LONG);
        saved.show();
        Intent i = new Intent(getBaseContext(), com.example.stimulus.SedentaryStimulus.class);
        PendingIntent pi = PendingIntent.getBroadcast(getBaseContext(), R.integer.alarm_rc, i, PendingIntent.FLAG_UPDATE_CURRENT);
        am.cancel(pi);
        setUpClock();
    }


    @Override
    public void onSensorChanged(SensorEvent event) {
        //Google API Activity Detection client??
        //2 Manual options and an existing (API) option

        int moved = 0;

        Log.d("ACCEL", "SENSOR EVENT");

        for(int i = 0; i < history.length; i++) {
            if (-0.2 > (history[i] - event.values[i])
                    || (history[i] - event.values[i]) > 0.2) {
                moved++;
            }
        }
            for(int i = 0; i < history.length; i++){
            history[i] = event.values[i];
            }

            if(moved >= 2) {
                if(((event.timestamp - historyTime)/1000/1000/1000) > 60){
                    historyTime = event.timestamp;
                    minutes++;
                }
            } else if(minutes > prevMinutes){
                SharedPreferences sharedPref = this.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putInt(getString(R.string.daily_progress), minutes);
                editor.commit();
                prevMinutes = minutes;
                monitor();
            }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}