package com.utopiaindustries.qualitychecker.ui.adapter;

import android.text.Editable;
import android.text.TextWatcher;
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.ImageButton;
import android.widget.Spinner;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.utopiaindustries.qualitychecker.R;
import com.utopiaindustries.qualitychecker.models.InspectionItemDimension;

import java.util.List;

public class DimensionAdapter extends
        RecyclerView.Adapter<DimensionAdapter.DimensionAdapterViewHolder>{

    private final List<InspectionItemDimension> dimensions;
    private final List<String> dimensionTypes;
    private final List<String> dimensionUnits;
    String[] dimensionUnitArray = {"CM", "INCH"};

    public DimensionAdapter(List<InspectionItemDimension> dimensions, List<String> dimensionTypes, List<String> dimensionUnits) {
        this.dimensions = dimensions;
        this.dimensionTypes = dimensionTypes;
        this.dimensionUnits = java.util.Arrays.asList(dimensionUnitArray);//dimensionUnits;
    }

    @NonNull
    @Override
    public DimensionAdapter.DimensionAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.dimension_item , parent, false);
        return new DimensionAdapterViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DimensionAdapterViewHolder holder, int position) {
        InspectionItemDimension item = dimensions.get( position );
        holder.bind( item , dimensionTypes , dimensionUnits ) ;
        holder.deleteItemBtn.setOnClickListener( v ->{
            removeItem( holder.getAdapterPosition() );
        });
    }

    @Override
    public int getItemCount() {
        return dimensions.size();
    }

    public void removeItem(int position) {
        if( position >= 0 && position < dimensions.size() ){
            dimensions.remove(position);
            notifyItemRemoved(position);
        }
    }


    public static class DimensionAdapterViewHolder extends RecyclerView.ViewHolder {

        private final Spinner dimensionTypeSpinner,dimensionUnitSpinner;
        private final EditText requiredEditText,actualEditText,differenceEditText;
        private final ImageButton deleteItemBtn;

        public DimensionAdapterViewHolder(@NonNull View itemView) {
            super(itemView);
            dimensionTypeSpinner = itemView.findViewById( R.id.dimension_type_spinner );
            dimensionUnitSpinner = itemView.findViewById( R.id.dimension_unit_spinner );
            requiredEditText = itemView.findViewById( R.id.required );
            actualEditText = itemView.findViewById( R.id.actual );
            differenceEditText = itemView.findViewById( R.id.difference );
            deleteItemBtn = itemView.findViewById( R.id.dimension_item_delete );
        }

        public void bind( InspectionItemDimension dimension ,
                          List<String> dimensionTypes,
                          List<String> dimensionUnits ){

            // Populate dimension type Spinner dropdown
            ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(dimensionTypeSpinner.getContext(),
                    android.R.layout.simple_spinner_item, dimensionTypes  );
            spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dimensionTypeSpinner.setAdapter(spinnerAdapter);

            String defaultSelection = dimension.getType();
            int defaultSelectedPosition = dimensionTypes.indexOf(defaultSelection);
            dimensionTypeSpinner.setSelection(defaultSelectedPosition);

            // Populate dimension unit Spinner dropdown
            ArrayAdapter<String> unitSpinnerAdapter = new ArrayAdapter<>(dimensionUnitSpinner.getContext(),
                    android.R.layout.simple_spinner_item, dimensionUnits  );
            unitSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dimensionUnitSpinner.setAdapter(unitSpinnerAdapter);

            String defaultUnitSelection = dimension.getUnit();
            int defaultItemSelectedPosition = dimensionUnits.indexOf(defaultUnitSelection);
            dimensionUnitSpinner.setSelection(defaultItemSelectedPosition);


            requiredEditText.setText( String.valueOf( dimension.getRequired() ));
            actualEditText.setText( String.valueOf( dimension.getActual() ));
            differenceEditText.setText( String.valueOf( dimension.getDifference() ));

            // Spinner listener
            {
                dimensionTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        String selectedItem = parent.getItemAtPosition(position).toString();
                        dimension.setType( selectedItem );
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });
            }
            // unit spinner
            {
                dimensionUnitSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        String selectedItem = parent.getItemAtPosition(position).toString();
                        dimension.setUnit( selectedItem );
                    }

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

            //  edit text listeners
            {
                requiredEditText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        try {
                            dimension.setRequired( Float.parseFloat( s.toString() ) );
                            float difference = dimension.getActual() - dimension.getRequired();
                            differenceEditText.setText( String.valueOf( difference ));
                            dimension.setDifference( difference );
                        } catch ( Exception e ){
                            differenceEditText.setText( "0" );
                            dimension.setDifference( 0 );
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });

                actualEditText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        try {
                            dimension.setActual( Float.parseFloat( s.toString() ) );
                            float difference = dimension.getActual() - dimension.getRequired();
                            differenceEditText.setText( String.valueOf( difference ));
                            dimension.setDifference( difference );
                        } catch ( Exception e ){
                            differenceEditText.setText( "0" );
                            dimension.setDifference( 0 );
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });
            }
        }
    }
}
