package org.deke.risk.riskahead.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.google.firebase.crashlytics.FirebaseCrashlytics;

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;

/**
 *
 * (C) Copyright 2016 RiskAhead (http://www.riskahead.net)
 * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net)
 * Date of Release: 10.02.2016
 *
 */
public class ReportWF_1_Fragment extends BaseReportWFFragment{
    private final static int VIOLANCE_THREAT = 1;
    private final static int VIOLANCE_PHYSICAL = 2;
    private final static int VIOLANCE_LIFETHREAT = 3;
    private final static int VIOLANCE_DISASTER = 4;

    private final static String TAG = ReportWF_1_Fragment.class.getSimpleName();

    private View viewFragment;

    private Spinner crimeCategory;
    private Spinner crimeSubCategory;
    private EditText crimeSubOther;

    private RelativeLayout timeLayout;
    private TextView txtPositionInformation;

    private IncidentReport incident;

    private OnInputFinishedListener mCallbackFinished;

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

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

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

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

        return viewFragment;
    }

    @Override
    public IncidentReport getCurrentInput() {
        saveInput();
        return incident;
    }

    private void initInputElements() {
        crimeCategory = viewFragment.findViewById(R.id.dd_reportwf_1_cat_main);
        crimeSubCategory = viewFragment.findViewById(R.id.dd_reportwf_1_cat_sub);
        crimeSubOther = viewFragment.findViewById(R.id.txt_reportwf_1_cat_etc);
        timeLayout = viewFragment.findViewById(R.id.ll_pos);
        txtPositionInformation = viewFragment.findViewById(R.id.lbl_reportwf_position_detail);

        crimeSubCategory.setVisibility(View.INVISIBLE);
        crimeSubOther.setVisibility(View.INVISIBLE);
        timeLayout.setVisibility(View.INVISIBLE);

        ReportWFActivity activity = (ReportWFActivity) getActivity();
        if(activity != null){
            activity.setMapButtonVisibility(false);
        }else{
            FirebaseCrashlytics.getInstance().log("Could not get parent activity");
        }


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

                switch (position) {
                    case 1:
                        stringId = R.array.cat_situation_sub_threat;
                        break;
                    case 2:
                        stringId = R.array.cat_situation_sub_physical;
                        break;
                    case 3:
                        stringId = R.array.cat_situation_sub_lifethreat;
                        break;
                    case 4:
                        stringId = R.array.cat_situation_sub_disaster;
                        break;
                    default:
                        stringId = R.array.cat_situation_sub_threat;
                        break;
                }

                if (((SpinnerHintAdapter) parent.getAdapter()).isInInitialState() && incident.getFidIncidentSubCategory() < 1) {
                    crimeSubCategory.setVisibility(View.INVISIBLE);
                    incident.setFidIncidentSubCategory(0);
                } else {
                    crimeSubCategory.setVisibility(View.VISIBLE);
                    setSubSpinnerValues(stringId);

                    checkIfFinished();
                }
            }

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


        crimeSubCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if (((SpinnerHintAdapter) parent.getAdapter()).isInInitialState()) {
                    crimeSubOther.setVisibility(View.INVISIBLE);
                } else {
                    timeLayout.setVisibility(View.VISIBLE);
                    crimeSubOther.setVisibility(View.VISIBLE);

                    ((ReportWFActivity) getActivity()).setMapButtonVisibility(true);
                    checkIfFinished();
                }
            }

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

    }

    private void setMainSpinnerValues(int stringId) {
        ReportWFActivity activity = (ReportWFActivity) getActivity();
        if(activity != null){
            ArrayAdapter<CharSequence> adapter_main_1 = ArrayAdapter.createFromResource(activity, stringId, android.R.layout.simple_spinner_dropdown_item);
            crimeCategory.setAdapter(new SpinnerHintAdapter(adapter_main_1, R.layout.contact_spinner_row_nothing_selected, activity));
        }else{
            FirebaseCrashlytics.getInstance().log("Could not get parent activity");
        }

    }

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

        if(incident.getFidIncidentSubCategory() > 0) crimeSubCategory.setSelection(incident.getFidIncidentSubCategory());
    }

    private void checkIfFinished(){
        boolean mainCategoryIsFilled = false;
        boolean subCategoryIsFilled = false;
        boolean positionIsFilled = false;

        if(incident != null){
            mainCategoryIsFilled = (crimeCategory.getSelectedItemPosition() > 0);

            subCategoryIsFilled = (crimeSubCategory.isShown()) && (crimeSubCategory.getSelectedItemPosition() > 0);

            positionIsFilled = (timeLayout.isShown() && incident.getPosition() != null);
        }

        boolean isFinished = mainCategoryIsFilled && subCategoryIsFilled && positionIsFilled;

        mCallbackFinished.onInputFinished(isFinished);
    }

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

        ReportWFActivity activity = (ReportWFActivity) getActivity();
        if(activity != null){
            incident = activity.getIncident();
        }else{
            FirebaseCrashlytics.getInstance().log("Could not get parent activity");
        }

        if(incident != null){
            if(incident.getFidIncidentCategory() > 0){
                crimeCategory.setSelection(incident.getFidIncidentCategory());
            }

            if(incident.getFidIncidentSubCategory() > 0){
                crimeSubCategory.setSelection(incident.getFidIncidentSubCategory());
            }

            if(incident.getPosition() != null){
                timeLayout.setVisibility(View.VISIBLE);
                txtPositionInformation.setText(incident.getIncidentPositionDescription());
                ((ReportWFActivity)getActivity()).setMapButtonVisibility(true);
            }

            if (!incident.getEtcIncidentCategory().equals("")){
                crimeSubOther.setText(incident.getEtcIncidentCategory());
            }
        }

        checkIfFinished();
    }

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

        saveInput();
    }

    public void saveInput() {
        incident.setFidIncidentCategory(crimeCategory.getSelectedItemPosition());
        incident.setFidIncidentSubCategory(crimeSubCategory.getSelectedItemPosition());
        incident.setEtcIncidentCategory(crimeSubOther.getText().toString());

        ReportWFActivity activity = (ReportWFActivity) getActivity();
        if(activity != null){
            activity.setIncident(incident);
        }else{
            FirebaseCrashlytics.getInstance().log("Could not get parent activity");
        }
    }

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

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

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