package com.rdiot.yx485.adapter;

import android.text.TextUtils;
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.bumptech.glide.Glide;
import com.rdiot.yx485.R;
import com.rdiot.yx485.bean.DeviceTreeBean;
import com.rdiot.yx485.http.Url;

import java.util.List;

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

    private final List<DeviceTreeBean.DataBean.ChildrenBean> mData;
    private final OnItemClickListener mListener;

    public DeviceTypeListAdapter(List<DeviceTreeBean.DataBean.ChildrenBean> data, OnItemClickListener listener) {
        mData = data;
        mListener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.setIsRecyclable(false);
        holder.bindData(position);
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    public interface OnItemClickListener {
        void onItemClick(DeviceTreeBean.DataBean.ChildrenBean item);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private final ImageView icon;
        private final TextView text;

        ViewHolder(View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.icon);
            text = itemView.findViewById(R.id.text);
        }

        public void bindData(int position) {
            DeviceTreeBean.DataBean.ChildrenBean bean = mData.get(position);
            if (bean == null) {
                return;
            }

            if (!TextUtils.isEmpty(bean.name)) {
                text.setText(bean.name);
            }

            if (bean.icon != null) {
                Glide.with(icon.getContext())
                        .load(Url.BASE_URL + bean.icon)
                        .error(Glide.with(icon.getContext()).load(R.drawable.find_d))
                        .into(icon);
            }

            itemView.setOnClickListener(v -> {
                if (mListener != null) {
                    mListener.onItemClick(bean);
                }
            });
        }
    }
}