package it.integry.integrywmsnative.gest.main;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.class_router.configs.MenuConfiguration;

public class MenuListAdapter extends RecyclerView.Adapter<MenuListAdapter.ViewHolder> {

    private Context mContext;

    private List<MenuConfiguration.MenuItem> mDataset;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MenuListAdapter(Context context, List<MenuConfiguration.MenuItem> data) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(context);
        this.mDataset = data;
    }

    // inflates the cell layout from xml when needed
    @Override
    @NonNull
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.fragment_main_menu_item_layout, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each cell
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.mIcon.setImageDrawable(ResourcesCompat.getDrawable(mContext.getResources(), mDataset.get(position).getTitleIcon(), null));
        holder.mTitle.setText(mContext.getResources().getString(mDataset.get(position).getTitleText()));
    }

    // total number of cells
    @Override
    public int getItemCount() {
        return mDataset.size();
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView mTitle;
        private ImageView mIcon;

        ViewHolder(View itemView) {
            super(itemView);
            mTitle = itemView.findViewById(R.id.menu_title);
            mIcon = itemView.findViewById(R.id.menu_icon);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }


    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}
