/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.ui;//这个类包含在 net.micode.notes.ui包里

import java.text.DateFormatSymbols;
import java.util.Calendar;//引用日历

import net.micode.notes.R;


import android.content.Context;//文本环境
import android.text.format.DateFormat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.NumberPicker;//可以使用数据选择器设置数字

public class DateTimePicker extends FrameLayout {//获取并分析当前具体时间

    private static final boolean DEFAULT_ENABLE_STATE = true;//定义常量

    private static final int HOURS_IN_HALF_DAY = 12;//定义常量，半天12小时
    private static final int HOURS_IN_ALL_DAY = 24;//定义常量，全天24小时
    private static final int DAYS_IN_ALL_WEEK = 7;//定义常量，一周7天
    private static final int DATE_SPINNER_MIN_VAL = 0;//定义常量，日期最小循环值为0
    private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;//定义常量，日期最大循环值为6
    private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;//定义常量，24小时制最小循环值为0
    private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;//定义常量，24小时最大循环值为23
    private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;//定义常量，12小时最小循环值为1
    private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;//定义常量，12小时最小循环值为12
    private static final int MINUT_SPINNER_MIN_VAL = 0;//定义常量，分钟最小循环值为0
    private static final int MINUT_SPINNER_MAX_VAL = 59;//定义常量，分钟最大循环值为25
    private static final int AMPM_SPINNER_MIN_VAL = 0;//定义常量，上下午的最小循环值为0
    private static final int AMPM_SPINNER_MAX_VAL = 1;//定义常量，上下午的最大循环值为1

    private final NumberPicker mDateSpinner;//定义只能更改一次的变量，与闹钟的日期设置有关
    private final NumberPicker mHourSpinner;//定义只能更改一次的变量，与闹钟的小时设置有关
    private final NumberPicker mMinuteSpinner;//定义只能更改一次的变量，与闹钟的分钟设置有关
    private final NumberPicker mAmPmSpinner;//定义只能更改一次的变量，与闹钟的上下午设置有关
    private Calendar mDate;//定义Calendar类型的变量mDate，用于操作时间

    private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];//定义一个展示时间的字符串

    private boolean mIsAm;//定义变量表示是否是上午

    private boolean mIs24HourView;//定义变量表示是否是24小时制

    private boolean mIsEnabled = DEFAULT_ENABLE_STATE;//定义变量判断日期时间选择器是否已经启用

    private boolean mInitialising;//定义变量表示是否在初始化

    private OnDateTimeChangedListener mOnDateTimeChangedListener;//定义日期时间变化监听器

    private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);//根据日期新旧值，改变日历
            updateDateControl();//同步更新日期
            onDateTimeChanged();//监听日期时间变化
        }//重写监听日期值变化的方法
    };//监听日期变化，传送给mDate并进行同步更新操作

    private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            boolean isDateChanged = false;//默认时间没有变化
            Calendar cal = Calendar.getInstance();//创建一个日历
            if (!mIs24HourView) {//这里是针对12小时制的操作
                if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {//在夜晚11时变化到夜晚12时的时候更新
                    cal.setTimeInMillis(mDate.getTimeInMillis());//将参数的值作为系统时间
                    cal.add(Calendar.DAY_OF_YEAR, 1);//加一天
                    isDateChanged = true;//表示日期发生变化
                } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {//当由夜晚12点变回11点时
                    cal.setTimeInMillis(mDate.getTimeInMillis());
                    cal.add(Calendar.DAY_OF_YEAR, -1);//减一天
                    isDateChanged = true;
                }
                if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
                        oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {//上半天的时钟处理，中午12更新
                    mIsAm = !mIsAm;//上下午标志转换
                    updateAmPmControl();//调用函数更新上下午
                }
            } else {//如果是24小时制则
                if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {//晚上23点和0点交替时对日期的更改
                    cal.setTimeInMillis(mDate.getTimeInMillis());
                    cal.add(Calendar.DAY_OF_YEAR, 1);//加一天
                    isDateChanged = true;
                } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {//0点变为23点时对日期的更改
                    cal.setTimeInMillis(mDate.getTimeInMillis());
                    cal.add(Calendar.DAY_OF_YEAR, -1);//减一天
                    isDateChanged = true;
                }
            }
            int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);//获得当前小时转轮表示的时间并转化为相应小时制
            mDate.set(Calendar.HOUR_OF_DAY, newHour);//设置新的小时数
            onDateTimeChanged();//监听时间变化
            if (isDateChanged) {
                setCurrentYear(cal.get(Calendar.YEAR));
                setCurrentMonth(cal.get(Calendar.MONTH));
                setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
            }//如果日期发生变化则设置新日期
        }//改变小时，更新天数
    };//监听时钟变化，以小时为单位

    private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            int minValue = mMinuteSpinner.getMinValue();
            int maxValue = mMinuteSpinner.getMaxValue();
            int offset = 0;//定义offset小时偏移量 根据新旧时间的变化情况来加一或者是减一
            if (oldVal == maxValue && newVal == minValue) {//分钟数从最大变到最小则小时偏移量加1
                offset += 1;
            } else if (oldVal == minValue && newVal == maxValue) {//分钟数从最小变到最大则小时偏移量减1
                offset -= 1;
            }
            if (offset != 0) {//如果存在时间偏移量，对时间进行修改
                mDate.add(Calendar.HOUR_OF_DAY, offset);//根据分钟变化修改小时的计数
                mHourSpinner.setValue(getCurrentHour());//获取当前时间来确定小时轮转数
                updateDateControl();
                int newHour = getCurrentHourOfDay();//得到现在的小时数，来决定是否修改am 或是pm
                if (newHour >= HOURS_IN_HALF_DAY) {//根据新计算的小时数是否超过12小时，更新上下午控制
                    mIsAm = false;
                    updateAmPmControl();
                } else {//新时间在12点前为上午
                    mIsAm = true;
                    updateAmPmControl();
                }
            }
            mDate.set(Calendar.MINUTE, newVal);//更新分钟数
            onDateTimeChanged();//监听时间变化
        }//对分钟时间进行监听，并根据变化做出修改
    };

    private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {//实例化上下午变化监听器
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {//监听am与pm的变化，并根据情况修改日期的小时数
            mIsAm = !mIsAm;
            if (mIsAm) {//下午变到上午，小时数减12
                mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
            } else {//上午变到下午，小时数加12
                mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
            }
            updateAmPmControl();
            onDateTimeChanged();
        }
    };

    public interface OnDateTimeChangedListener {//接口：日期变化监听器
        void onDateTimeChanged(DateTimePicker view, int year, int month,
                int dayOfMonth, int hourOfDay, int minute);//时间变化监听器函数的定义
    }

    public DateTimePicker(Context context) {//构造函数,实例化时间日期选择器
        this(context, System.currentTimeMillis());
    }

    public DateTimePicker(Context context, long date) {//构造函数,获取系统的时间
        this(context, date, DateFormat.is24HourFormat(context));
    }

    public DateTimePicker(Context context, long date, boolean is24HourView) {//构造函数,实例化时间日期选择器
        super(context);
        mDate = Calendar.getInstance();//获取系统时间
        mInitialising = true;
        mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
        inflate(context, R.layout.datetime_picker, this);//找出对话框的布局

        mDateSpinner = (NumberPicker) findViewById(R.id.date);//显示设置日期的视图
        mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);//设置组件最小值属性为日期最小值
        mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);//设置组件最大值属性为日期最大值
        mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);

        mHourSpinner = (NumberPicker) findViewById(R.id.hour);//显示设置小时的视图
        mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
        mMinuteSpinner =  (NumberPicker) findViewById(R.id.minute);//显示设置分钟的视图
        mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);//设置组件最小值属性为分钟最小值
        mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);//设置组件最大值属性为分钟最大值
        mMinuteSpinner.setOnLongPressUpdateInterval(100);//设置监听长按时间间隔为100ms
        mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);

        String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();//对24小时制下的 am 与pm各属性值进行初始化
        mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);//显示设置上下午的视图
        mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);//设置组件最小值属性为上下午编码最小值
        mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);//设置组件最大值属性为上下午编码最大值
        mAmPmSpinner.setDisplayedValues(stringsForAmPm);//设置显示上下午字符串的值
        mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);

        // update controls to initial state,将日期的各参数更新为初始化状态
        updateDateControl();
        updateHourControl();
        updateAmPmControl();

        set24HourView(is24HourView);//根据用户选择设置是否为24小时制显示，否则为12小时制显示

        // set to current time,设置当前日期
        setCurrentDate(date);

        setEnabled(isEnabled());

        // set the content descriptions,表示初始化已经结束
        mInitialising = false;
    }

    @Override
    public void setEnabled(boolean enabled) {//将当前监听器的状态设置为开启状态
        if (mIsEnabled == enabled) {//如果已经在使能状态，则返回
            return;
        }
        super.setEnabled(enabled);//调用父类方法
        mDateSpinner.setEnabled(enabled);//分别对四个分部件设置使能
        mMinuteSpinner.setEnabled(enabled);
        mHourSpinner.setEnabled(enabled);
        mAmPmSpinner.setEnabled(enabled);
        mIsEnabled = enabled;
    }

    @Override
    public boolean isEnabled() {
        return mIsEnabled;
    }//判断时间日期选择器是否处于使能状态

    /**
     * Get the current date in millis
     *
     * @return the current date in millis
     */
    public long getCurrentDateInTimeMillis() {
        return mDate.getTimeInMillis();
    }//获取当前时间，以毫秒表示

    /**
     * Set the current date
     *
     * @param date The current date in millis
     */
    public void setCurrentDate(long date) {//设置当前日期
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(date);
        setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
                cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));//设置当前日期
    }

    /**
     * Set the current date
     *
     * @param year The current year
     * @param month The current month
     * @param dayOfMonth The current dayOfMonth
     * @param hourOfDay The current hourOfDay
     * @param minute The current minute
     */
    public void setCurrentDate(int year, int month,
            int dayOfMonth, int hourOfDay, int minute) {//设置当前日期（直接使用日期和时间的参数）
        setCurrentYear(year);
        setCurrentMonth(month);
        setCurrentDay(dayOfMonth);
        setCurrentHour(hourOfDay);
        setCurrentMinute(minute);
    }

    /**
     * Get current year
     *
     * @return The current year
     */
    public int getCurrentYear() {
        return mDate.get(Calendar.YEAR);
    }//获取当前年份

    /**
     * Set current year
     *
     * @param year The current year
     */
    public void setCurrentYear(int year) {//设置当前年份
        if (!mInitialising && year == getCurrentYear()) {//如果已初始化且当前年份和真实年份相同，则不需设置
            return;
        }
        mDate.set(Calendar.YEAR, year);
        updateDateControl();
        onDateTimeChanged();
    }

    /**
     * Get current month in the year
     *
     * @return The current month in the year
     */
    public int getCurrentMonth() {
        return mDate.get(Calendar.MONTH);
    }//获取当前月份

    /**
     * Set current month in the year
     *
     * @param month The month in the year
     */
    public void setCurrentMonth(int month) {//设置当前月份
        if (!mInitialising && month == getCurrentMonth()) {//若输入月份等于当前月份则返回
            return;
        }
        mDate.set(Calendar.MONTH, month);//修改月份
        updateDateControl();
        onDateTimeChanged();
    }

    /**
     * Get current day of the month
     *
     * @return The day of the month
     */
    public int getCurrentDay() {
        return mDate.get(Calendar.DAY_OF_MONTH);
    }//获取当前日期

    /**
     * Set current day of the month
     *
     * @param dayOfMonth The day of the month
     */
    public void setCurrentDay(int dayOfMonth) {//设置当前日期
        if (!mInitialising && dayOfMonth == getCurrentDay()) {
            return;
        }
        mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        updateDateControl();
        onDateTimeChanged();
    }

    /**
     * Get current hour in 24 hour mode, in the range (0~23)
     * @return The current hour in 24 hour mode
     */
    public int getCurrentHourOfDay() {
        return mDate.get(Calendar.HOUR_OF_DAY);
    }//在24小时制下获取当天的小时数

    private int getCurrentHour() {//获取当前小时数
        if (mIs24HourView){//获取当前小时数
            return getCurrentHourOfDay();
        } else {//否则返回12小时制的小时数
            int hour = getCurrentHourOfDay();
            if (hour > HOURS_IN_HALF_DAY) {
                return hour - HOURS_IN_HALF_DAY;
            } else {
                return hour == 0 ? HOURS_IN_HALF_DAY : hour;
            }
        }
    }

    /**
     * Set current hour in 24 hour mode, in the range (0~23)
     *
     * @param hourOfDay
     */
    public void setCurrentHour(int hourOfDay) {//在24小时制下设置小时数
        if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
            return;
        }
        mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
        if (!mIs24HourView) {//如果为12小时制，则根据12小时制下的数修改为对应24小时制下的数
            if (hourOfDay >= HOURS_IN_HALF_DAY) {
                mIsAm = false;
                if (hourOfDay > HOURS_IN_HALF_DAY) {
                    hourOfDay -= HOURS_IN_HALF_DAY;
                }
            } else {
                mIsAm = true;
                if (hourOfDay == 0) {
                    hourOfDay = HOURS_IN_HALF_DAY;
                }
            }
            updateAmPmControl();
        }
        mHourSpinner.setValue(hourOfDay);
        onDateTimeChanged();
    }

    /**
     * Get currentMinute
     *
     * @return The Current Minute
     */
    public int getCurrentMinute() {
        return mDate.get(Calendar.MINUTE);
    }//获取当前分钟数

    /**
     * Set current minute
     */
    public void setCurrentMinute(int minute) {//设置当前分钟数
        if (!mInitialising && minute == getCurrentMinute()) {
            return;
        }
        mMinuteSpinner.setValue(minute);
        mDate.set(Calendar.MINUTE, minute);
        onDateTimeChanged();
    }

    /**
     * @return true if this is in 24 hour view else false.
     */
    public boolean is24HourView () {
        return mIs24HourView;
    }//返回是否是24小时制的时间

    /**
     * Set whether in 24 hour or AM/PM mode.
     *
     * @param is24HourView True for 24 hour mode. False for AM/PM mode.
     */
    public void set24HourView(boolean is24HourView) {//设置24小时下的视图
        if (mIs24HourView == is24HourView) {
            return;
        }
        mIs24HourView = is24HourView;
        mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);//如果是12小时制则显示上午还是下午
        int hour = getCurrentHourOfDay();
        updateHourControl();
        setCurrentHour(hour);
        updateAmPmControl();
    }

    private void updateDateControl() {//更新日期控制
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(mDate.getTimeInMillis());
        cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);//加一天
        mDateSpinner.setDisplayedValues(null);
        for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
        }
        mDateSpinner.setDisplayedValues(mDateDisplayValues);
        mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
        mDateSpinner.invalidate();//使日期转轮失效
    }

    private void updateAmPmControl() {//对上下午的操作
        if (mIs24HourView) {//24小时制的显示下，使得am与pm的转换在屏幕上不可见
            mAmPmSpinner.setVisibility(View.GONE);
        } else {//根据时间得到am或者pm，并且在屏幕上显示
            int index = mIsAm ? Calendar.AM : Calendar.PM;
            mAmPmSpinner.setValue(index);
            mAmPmSpinner.setVisibility(View.VISIBLE);
        }
    }

    private void updateHourControl() {//更新小时控制
        if (mIs24HourView) {//根据当前小时制设置时间
            mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
            mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
        } else {
            mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
            mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
        }
    }

    /**
     * Set the callback that indicates the 'Set' button has been pressed.
     * @param callback the callback, if null will do nothing
     */
    public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {//设置时间日期监听器
        mOnDateTimeChangedListener = callback;
    }

    private void onDateTimeChanged() {//监听日期时间变化
        if (mOnDateTimeChangedListener != null) {//输入年月日时分秒
            mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
                    getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
        }
    }
}
