package com.example.countdown;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.DatePicker;

public class DatePreference extends DialogPreference
                            implements DatePicker.OnDateChangedListener {
	private DatePicker datePicker;
	private int year;
	private int month;
	private int day;

	public DatePreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		datePicker = new DatePicker(getContext());
	}

	public DatePreference(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		datePicker = new DatePicker(getContext());
	}
	
	@Override
	protected View onCreateDialogView() {
	    //int thisYear = Calendar.getInstance().get(Calendar.YEAR);
	    //GregorianCalendar cal =
	    //        new GregorianCalendar(thisYear, Calendar.DECEMBER, 25);
	    //long timeVal = cal.getTimeInMillis();
	    //timeVal = PreferenceManager.getDefaultSharedPreferences(getContext()).getLong(CountdownActivity.DATE_PREF_KEY, timeVal);
		//datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), this);
		return datePicker;
	}
	
	@Override
	protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
		super.onSetInitialValue(restorePersistedValue, defaultValue);
		if (restorePersistedValue) {
	      int thisYear = Calendar.getInstance().get(Calendar.YEAR);
	      GregorianCalendar cal =
	            new GregorianCalendar(thisYear, Calendar.DECEMBER, 25);
	      long timeVal = cal.getTimeInMillis();
	      timeVal = PreferenceManager.getDefaultSharedPreferences(getContext()).getLong(CountdownActivity.DATE_PREF_KEY, timeVal);
	      cal.setTimeInMillis(timeVal);
	      this.year = cal.get(Calendar.YEAR);
	      this.month = cal.get(Calendar.MONTH);
	      this.day = cal.get(Calendar.DAY_OF_MONTH);
	      datePicker.setCalendarViewShown(false);
	  	  datePicker.init(year, month, day, this);
		}
	}

	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
		this.year = year;
		this.month = monthOfYear;
		this.day = dayOfMonth;
	}

	@Override
	protected void onDialogClosed(boolean positiveResult) {
		super.onDialogClosed(positiveResult);
		if (positiveResult) {
          GregorianCalendar cal =
                new GregorianCalendar(year, month, day);
          SharedPreferences.Editor editor = getEditor();
          editor.putLong(CountdownActivity.DATE_PREF_KEY, cal.getTimeInMillis()).commit();
		}
	}

}
