package com.yidianling.user.mine;

import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import com.ydl.ydlcommon.base.BaseOldDialogFragment;
import com.yidianling.user.R;

import java.util.Calendar;


/**
 * 日期选择器 dialog
 * Created by Dog on 2015/6/12.
 */
public class DatePickerDialogFragment extends BaseOldDialogFragment implements DatePicker.OnDateChangedListener {

    DatePicker dp_birthday;

    Calendar calendar = Calendar.getInstance();
    DatePicker.OnDateChangedListener dateChangedListener;
    int year, month, day;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.user_mine_fragment_dialog_date_picker,container,false);
        dp_birthday = view.findViewById(R.id.dp_birthday);
        view.findViewById(R.id.btn_cancel).setOnClickListener(v -> {
            dismiss();
        });
        view.findViewById(R.id.btn_sure).setOnClickListener(v -> {
            if (this.dateChangedListener != null) {
                dateChangedListener.onDateChanged(dp_birthday, dp_birthday.getYear(), dp_birthday.getMonth(), dp_birthday.getDayOfMonth());
            }
            dismiss();
        });
        init();
        return view;
    }

    public void setCalendar(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
        calendar.set(year, month, day);
    }

    public void setDateChangedListener(DatePicker.OnDateChangedListener listener) {
        this.dateChangedListener = listener;
    }

    void init() {
        dp_birthday.init(
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH),
                this
        );


    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        if (isDataAfter(view)) {
            Calendar mCalendar = Calendar.getInstance();
            view.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);
        }
    }

    private boolean isDataAfter(DatePicker datePicker) {
        Calendar mCalendar = Calendar.getInstance();
        Calendar tempCalendar = Calendar.getInstance();
        tempCalendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 0, 0, 0);
        if (tempCalendar.after(mCalendar)) {
            return true;
        } else {
            return false;
        }
    }


}
