package com.androidbegin.buttonclicktutorial;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TimePicker;
 
//https://www.androidtutorialpoint.com/basics/android-alert-dialog-tutorial-working-time-picker-date-picker-list-dialogs/

public class TimePickerFragment extends DialogFragment  {
 
        private TimePicker timePicker;
        
        public interface TimeDialogListener 
        {
            void onFinishDialog(String time);
        }
        
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState)
        {
            View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_time_layout,null);
 
            timePicker = (TimePicker) v.findViewById(R.id.dialog_time_picker);
            
           
            Dialog dialog;
            AlertDialog.Builder builder = null;
            
            
            //return new android.support.v7.app.
            
            
           // AlertDialog.Builder(getActivity())
            builder.setView(v);
            builder.setTitle("title");
            
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() 
                    {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    int hour = 0;
                                    hour = timePicker.getCurrentHour();

                                    int minute = 0;
                                    
                                        minute = timePicker.getCurrentMinute();
                                    
                                    TimeDialogListener activity = (TimeDialogListener) getActivity();
                                    activity.onFinishDialog(updateTime(hour,minute));
                                    dismiss();
                                }
                            });
            
            
            
            return builder.create();
        }
 
    private String updateTime(int hours, int mins) {
 
        String timeSet = "";
        if (hours > 12) {
            hours -= 12;
            timeSet = "PM";
        } else if (hours == 0) {
            hours += 12;
            timeSet = "AM";
        } else if (hours == 12)
            timeSet = "PM";
        else
            timeSet = "AM";
 
       String minutes = "";
        if (mins < 10)
            minutes = "0" + mins;
        else
            minutes = String.valueOf(mins);
 
        String myTime = new StringBuilder().append(hours).append(':')
                .append(minutes).append(" ").append(timeSet).toString();
 
        return myTime;
    }
}