package de.sebse.fuplanner.fragments;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import de.sebse.fuplanner.R;
import de.sebse.fuplanner.fragments.ModulesFragment.OnModulesFragmentInteractionListener;
import de.sebse.fuplanner.services.KVV.types.Modules;
import de.sebse.fuplanner.tools.ui.ItemViewHolder;

/**
 * {@link RecyclerView.Adapter} that can display a {@link Modules.Module} and makes a call to the
 * specified {@link OnModulesFragmentInteractionListener}.
 */
class ModulesAdapter extends RecyclerView.Adapter<ItemViewHolder> {

    private Modules mValues;
    private final OnModulesFragmentInteractionListener mListener;

    ModulesAdapter(OnModulesFragmentInteractionListener listener) {
        mValues = null;
        mListener = listener;
    }

    public void setModules(Modules modules) {
        mValues = modules;
        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;
        Modules.Module module = mValues.getByIndex(holder.getAdapterPosition());
        holder.mTitle.setText(module.title);
        holder.mSubLeft.setText(module.semester);
        holder.mSubRight.setText(module.type);

        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.onModulesFragmentInteraction(module.getID());
            }
        });
    }

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