package de.sebse.fuplanner.fragments;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.fragments.CanteensFragment.OnCanteensFragmentInteractionListener;
import de.sebse.fuplanner.services.canteen.types.Canteen;
import de.sebse.fuplanner.services.canteen.types.Canteens;
import de.sebse.fuplanner.tools.ui.ItemViewHolder;

/**
 * {@link RecyclerView.Adapter} that can display a {@link Canteen} and makes a call to the
 * specified {@link OnCanteensFragmentInteractionListener}.
 */
class CanteensAdapter extends RecyclerView.Adapter<ItemViewHolder> {

    private Canteens mValues;
    private final OnCanteensFragmentInteractionListener mListener;

    CanteensAdapter(OnCanteensFragmentInteractionListener listener) {
        mValues = null;
        mListener = listener;
    }

    public void setCanteens(Canteens canteens) {
        mValues = canteens;
        this.notifyDataSetChanged();
    }

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

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
        if (mValues == null)
            return;
        Canteen canteen = mValues.get(holder.getAdapterPosition());
        holder.mTitle.setText(canteen.getName());
        holder.mSubLeft.setText(canteen.getAddress());
        holder.mSubRight.setText(canteen.getCity());

        holder.mView.setOnClickListener(v -> {
            if (null != mListener) {
                // Notify the active callbacks interface (the activity, if the
                // fragment is attached to one) that an item has been selected.
                mListener.onCanteensFragmentInteraction(canteen.getId());
            }
        });
    }

    @Override
    public int getItemCount() {
        if (mValues != null) {
            return mValues.size();
        }
        return 0;
    }
}
