package com.example.stopwatch;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.MotionEvent;
import java.util.Locale;

import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class MainActivity extends Activity {
    private int sec = 0;
    private boolean is_running;
    private boolean was_running;
    public static final String MyPREFERENCES = "MyPrefs" ;
    public String savedData = "";
    public String temp = null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView t_View = findViewById(R.id.time_view);

        // this is an example of putting a listener on a textView
        t_View.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onTimeShowPopupWindow(v);
            }
        });

        // retrieve saved timer values
        if (savedInstanceState != null) {
            sec = savedInstanceState.getInt("seconds");
            is_running = savedInstanceState.getBoolean("running");
            was_running = savedInstanceState .getBoolean("wasRunning");
        }
        running_Timer();
    }

    // preserves variable states when app is paused/resumed
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState)
    {
        savedInstanceState.putInt("seconds", sec);
        savedInstanceState.putBoolean("running", is_running);
        savedInstanceState.putBoolean("wasRunning", was_running);
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        was_running = is_running;
        is_running = false;
    }
    @Override
    protected void onResume()
    {
        super.onResume();
        if (was_running) {
            is_running = true;
        }
    }
    // UI interface button methods
    public void onClickStart(View view)
    {
        is_running = true;
    }
    public void onClickStop(View view)
    {
        is_running = false;
    }
    public void onClickReset(View view)
    {
        is_running = false;
        sec = 0;
    }
    // method to save the timer data
    public void onClickSave(View view)
    {
        // save the time to sharedpreferences
        TextView t_View = findViewById(R.id.time_view);
        temp = retrieveTime();
        if (temp.isEmpty()) temp = t_View.getText().toString().trim();
        else temp = temp + t_View.getText().toString();
        saveTime("time", temp);
    }
    // populates the TextView with the timer data
    private void running_Timer()
    {
        final TextView t_View = (TextView)findViewById(R.id.time_view);
        final Handler handle = new Handler();
        handle.post(new Runnable() {
            @Override
            public void run()
            {
                int hrs = sec / 3600;
                int mins = (sec % 3600) / 60;
                int secs = sec % 60;
                String time_t = String .format(Locale.getDefault(), "    %d:%02d:%02d   ", hrs,mins, secs);
                t_View.setText(time_t);
                if (is_running) { sec++; }
                handle.postDelayed(this, 1000);
            }
        });
    }

    // example for how to use shared preferences
    private void saveTime(String key, String value){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit(); // writes immediately
       //  editor.apply(); // writes in background
    }
    private String retrieveTime() {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        savedData = sharedPreferences.getString("time", "");
        return savedData;
    }
    private void clearTime(){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
    }

    // show a popup menu when the time TextView is pressed
    public void onTimeShowPopupWindow(View view) {
        // inflate the layout of the popup window
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View popupView = inflater.inflate(R.layout.popup, null);

        // get saved data and show on popup window
        savedData = retrieveTime();
        TextView times = popupView.findViewById(R.id.saved_times);
        times.setText(savedData);

        // instance of button on the popup window
        Button delete = (Button) popupView.findViewById(R.id.PopupBtn);
        delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // could close the window or do something else
                reset(); // shows an AlertDialog
            }
        });

        // create the popup window
        int width = LinearLayout.LayoutParams.WRAP_CONTENT;
        int height = LinearLayout.LayoutParams.WRAP_CONTENT;
        boolean focusable = true; // lets taps outside the popup also dismiss it

        final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

        // show the popup window
        // which view you pass in doesn't matter, it is only used for the window
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        popupWindow.setFocusable(true);

        // dismiss the popup window when touched
        popupView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                popupWindow.dismiss(); // popup closes if you press outside of it
                return true;
            }
        });
    }
    // example method that shows a confirmation dialog
    public void reset() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Confirm delete all data");
        builder.setMessage("All data will be erased. Are you sure?");

        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                clearTime();
                dialog.dismiss();
            }
        });

        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }
}
