package org.deke.risk.riskahead.fragment;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TimePicker;

import org.deke.risk.riskahead.R;
import org.deke.risk.riskahead.ReportWFActivity;
import org.deke.risk.riskahead.helper.IncidentReport;
import org.deke.risk.riskahead.adapter.SpinnerHintAdapter;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @author Dennis Thießen
 */
public class ReportWF_2_Fragment extends Fragment {

    private final static int NOW = 1;
    private final static int PERIODIC = 2;
    private final static int DATETIME = 3;
    private final static int DATETIMEAREA = 4;
    private final static int DONTKNOW = 5;

    private View viewFragment;

    private Spinner timeCategory;
    private Spinner timeSubCategory;

    private EditText inputTimeFrom;
    private EditText inputDateFrom;
    private EditText inputTimeTo;
    private EditText inputDateTo;

    private EditText tmpInput;

    private IncidentReport incident;

    private OnInputFinishedListener mCallback;

    public interface OnInputFinishedListener {
        void onInputFinished(boolean finished);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        viewFragment = inflater.inflate(R.layout.fragment_reportwf_2, container, false);

        initInputElements();
        setMainSpinnerValues(R.array.cat_time_main);

        return viewFragment;
    }

    private void initInputElements() {
        initLayoutFromDateTime();
        initLayoutToDateTime();

        timeCategory = (Spinner) viewFragment.findViewById(R.id.dd_reportwf_2_time_main);
        timeSubCategory = (Spinner) viewFragment.findViewById(R.id.dd_reportwf_2_time_sub);

        timeSubCategory.setVisibility(View.INVISIBLE);

        timeCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                int stringId = 0;
                resetDates();

                switch (position) {
                    case NOW:
                        viewFragment.findViewById(R.id.ll_report_from_time).setVisibility(View.INVISIBLE);
                        viewFragment.findViewById(R.id.ll_report_to_time).setVisibility(View.INVISIBLE);
                        viewFragment.findViewById(R.id.dd_reportwf_2_time_sub).setVisibility(View.INVISIBLE);

                        inputDateFrom.setText(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()));
                        inputTimeFrom.setText(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
                        break;
                    case PERIODIC:
                        viewFragment.findViewById(R.id.ll_report_from_time).setVisibility(View.INVISIBLE);
                        viewFragment.findViewById(R.id.ll_report_to_time).setVisibility(View.INVISIBLE);

                        stringId = R.array.cat_time_sub_periodical;
                        break;
                    case DATETIME:
                        viewFragment.findViewById(R.id.ll_report_from_time).setVisibility(View.VISIBLE);
                        viewFragment.findViewById(R.id.ll_report_to_time).setVisibility(View.INVISIBLE);
                        viewFragment.findViewById(R.id.dd_reportwf_2_time_sub).setVisibility(View.INVISIBLE);
                        break;
                    case DATETIMEAREA:
                        viewFragment.findViewById(R.id.ll_report_from_time).setVisibility(View.VISIBLE);
                        viewFragment.findViewById(R.id.ll_report_to_time).setVisibility(View.VISIBLE);
                        viewFragment.findViewById(R.id.dd_reportwf_2_time_sub).setVisibility(View.INVISIBLE);
                        break;
                    case DONTKNOW:
                        viewFragment.findViewById(R.id.ll_report_from_time).setVisibility(View.INVISIBLE);
                        viewFragment.findViewById(R.id.ll_report_to_time).setVisibility(View.INVISIBLE);
                        viewFragment.findViewById(R.id.dd_reportwf_2_time_sub).setVisibility(View.INVISIBLE);
                        break;
                }

                if (((SpinnerHintAdapter) timeCategory.getAdapter()).isInInitialState()) {
                    timeSubCategory.setVisibility(View.INVISIBLE);
                } else {
                    incident.setFidTimeCategory(position);

                    if (stringId != 0) {
                        timeSubCategory.setVisibility(View.VISIBLE);
                        setSubSpinnerValues(stringId);
                    }
                }

                checkIfFinished();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // do nothing
            }
        });

        timeSubCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if ((position < 1) && (incident.getFidTimeSubCategory() != 0))
                    timeSubCategory.setSelection(incident.getFidTimeSubCategory());

                incident.setFidTimeSubCategory(position);
                checkIfFinished();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void setMainSpinnerValues(int stringId) {
        ArrayAdapter<CharSequence> adapter_main_1 = ArrayAdapter.createFromResource(getActivity(), stringId , android.R.layout.simple_spinner_dropdown_item);
        timeCategory.setAdapter(new SpinnerHintAdapter(adapter_main_1, R.layout.contact_spinner_row_nothing_selected, getActivity()));
    }

    private void setSubSpinnerValues(int stringId) {
        ArrayAdapter<CharSequence> adapter_sub_1 = ArrayAdapter.createFromResource(viewFragment.getContext(), stringId, android.R.layout.simple_spinner_dropdown_item);
        timeSubCategory.setAdapter(new SpinnerHintAdapter(adapter_sub_1, R.layout.contact_spinner_row_nothing_selected, getActivity()));

        if(incident.getFidTimeSubCategory() > 0) timeSubCategory.setSelection(incident.getFidTimeSubCategory());
    }

    private void initLayoutFromDateTime() {
        RelativeLayout rlFromTime = (RelativeLayout) viewFragment.findViewById(R.id.ll_report_from_time);
        rlFromTime.setVisibility(View.INVISIBLE);

        inputDateFrom = ((EditText) viewFragment.findViewById(R.id.input_report_from_date));
        inputTimeFrom = ((EditText) viewFragment.findViewById(R.id.input_report_from_time));

        inputDateFrom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tmpInput = inputDateFrom;
                showDatePickerDialog();
            }
        });

        inputTimeFrom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tmpInput = inputTimeFrom;
                showTimePickerDialog();
            }
        });
    }

    private void initLayoutToDateTime() {
        RelativeLayout rlFromTime = (RelativeLayout) viewFragment.findViewById(R.id.ll_report_to_time);
        rlFromTime.setVisibility(View.INVISIBLE);

        inputDateTo = ((EditText) viewFragment.findViewById(R.id.input_report_to_date));
        inputTimeTo = ((EditText) viewFragment.findViewById(R.id.input_report_to_time));

        inputDateTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tmpInput = inputDateTo;
                showDatePickerDialog();
            }
        });

        inputTimeTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tmpInput = inputTimeTo;
                showTimePickerDialog();
            }
        });
    }

    public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            return new TimePickerDialog(getActivity(), this, hour, minute,DateFormat.is24HourFormat(getActivity()));
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            tmpInput.setText(new StringBuilder().append(hourOfDay)
                    .append(":").append(minute).append(" "));

            checkIfFinished();
        }
    }

    public void showTimePickerDialog() {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getActivity().getSupportFragmentManager(), "Pick Time");
    }

    public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            tmpInput.setText(new StringBuilder()
                    .append(year).append("-").append(month + 1).append("-")
                    .append(day).append(" "));

            checkIfFinished();
        }
    }

    public void showDatePickerDialog() {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getActivity().getSupportFragmentManager(), "Pick Date");
    }

    private void checkIfFinished(){
        boolean isTimeCategoryFilled = false;
        boolean isSubCategoryFilled = false;
        boolean isFromDateFilled = false;
        boolean isToDateFilled = false;

        if(incident != null){

            if((timeCategory.getSelectedItemPosition() > 0) && timeCategory.getVisibility() == View.VISIBLE){
                isTimeCategoryFilled = true;
            }

            if(timeSubCategory.isShown()){
                isSubCategoryFilled = (timeSubCategory.getSelectedItemPosition() > 0) && (incident.getFidTimeSubCategory() > 0);
            }else{
                isSubCategoryFilled = true;
            }

            if(inputDateFrom.isShown()){
                 isFromDateFilled = inputDateFrom.getText().toString().trim().length() > 0;
            }else{
                isFromDateFilled = true;
            }

            if(inputDateTo.isShown()){
                isToDateFilled = inputDateTo.getText().toString().trim().length() > 0;
            }else{
                isToDateFilled = true;
            }
        }

        mCallback.onInputFinished(isTimeCategoryFilled && isSubCategoryFilled && isFromDateFilled && isToDateFilled);
    }

    private void resetDates() {
        incident.resetDatetime();

        inputDateFrom.setText("");
        inputTimeFrom.setText("");
        inputDateTo.setText("");
        inputDateFrom.setText("");
    }

    @Override
    public void onResume() {
        super.onResume();

        incident = ((ReportWFActivity)getActivity()).getIncident();

        if(incident != null){
            if(incident.getFidTimeCategory() != 0){
                timeCategory.setSelection(incident.getFidTimeCategory());
                //SubCategory is automatically initialized
            }

            if(incident.getFromDate() != null && !incident.getFromDate().equals("")){
                inputDateFrom.setText(incident.getFromDate());
            }

            if(incident.getFromTime() != null && !incident.getFromTime().equals("")){
                inputTimeFrom.setText(incident.getFromTime());
            }

            if(incident.getToDate() != null && !incident.getToDate().equals("")){
                inputDateTo.setText(incident.getToDate());
            }

            if(incident.getToTime() != null && !incident.getToTime().equals("")){
                inputDateTo.setText(incident.getToDate());
            }
        }

        checkIfFinished();
    }

    @Override
    public void onPause() {
        super.onPause();

        incident.setFidTimeCategory(timeCategory.getSelectedItemPosition());
        incident.setFidTimeSubCategory(timeSubCategory.getSelectedItemPosition());
        incident.setFromDate(inputDateFrom.getText().toString());
        incident.setFromTime(inputTimeFrom.getText().toString());
        incident.setToDate(inputDateTo.getText().toString());
        incident.setToTime(inputTimeTo.getText().toString());

        ((ReportWFActivity)getActivity()).setIncident(incident);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        try {
            mCallback = (OnInputFinishedListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement OnInputFinishedListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}
