package jp.sourceforge.tamanegisoul.sa.widget;

import java.util.Calendar;
import java.util.Date;

import jp.sourceforge.tamanegisoul.sa.util.LogUtil;
import jp.sourceforge.tamanegisoul.sa.util.PreferenceUtils;

import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;

public class TimePreference extends DialogPreference {

    private TimePicker mTimePicker;
    private Calendar mCalendar;

    public TimePreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public TimePreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public CharSequence getSummary() {
        return PreferenceUtils.getString(getContext(), getKey());
    }

    @Override
    protected View onCreateDialogView() {
        mTimePicker = new TimePicker(getContext());
        mTimePicker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(getContext()));

        Date time = PreferenceUtils.getTime(getContext(), getKey());
        if (time == null)
            time = new Date();
        mCalendar = Calendar.getInstance();
        mCalendar.setTime(time);

        mTimePicker.setCurrentHour(mCalendar.get(Calendar.HOUR_OF_DAY));
        mTimePicker.setCurrentMinute(mCalendar.get(Calendar.MINUTE));
        return mTimePicker;
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        LogUtil.d("TimePreference.onDialogClosed(%s)", positiveResult);
        if (positiveResult) {
            mCalendar.set(Calendar.HOUR_OF_DAY, mTimePicker.getCurrentHour());
            mCalendar.set(Calendar.MINUTE, mTimePicker.getCurrentMinute());
            PreferenceUtils.setTime(getContext(), getKey(), mCalendar.getTime());
            setSummary(getSummary());
        }
        super.onDialogClosed(positiveResult);
    }

}
