package com.casic.dcms.adapter;

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.recyclerview.widget.RecyclerView;

import com.casic.dcms.R;
import com.casic.dcms.bean.HomePageBean;
import com.casic.dcms.utils.StringHelper;

import java.util.List;

public class HomeRecycleAdapter extends RecyclerView.Adapter<HomeRecycleAdapter.ItemViewHolder> {

    private final Context context;
    private final List<HomePageBean.DataBean.MenusBean> menuData;

    public HomeRecycleAdapter(Context context, List<HomePageBean.DataBean.MenusBean> menus) {
        this.context = context;
        this.menuData = menus;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
        String name = menuData.get(position).getName();
        holder.bindView(name);
        if (clickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickListener.onClick(name);
                }
            });
        }
    }

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

    private OnGridItemClickListener clickListener;

    public interface OnGridItemClickListener {
        void onClick(String itemName);
    }

    public void setOnGridItemClickListener(OnGridItemClickListener onGridItemClickListener) {
        this.clickListener = onGridItemClickListener;
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {

        private final ImageView imageView;
        private final TextView textView;

        ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            textView = itemView.findViewById(R.id.textView);
        }

        void bindView(String name) {
            imageView.setBackgroundResource(StringHelper.obtainIcon(name));
            textView.setText(name);
        }
    }
}
