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.RoomDeviceDetailBean;
import com.rdiot.yx485.http.Url;

import java.util.List;

public class RoomDeviceAdapter extends RecyclerView.Adapter<RoomDeviceAdapter.DeviceViewHolder> {

    private List<RoomDeviceDetailBean.RoomDeviceList.RoomDevice> devices;
    private OnItemClickListener listener;

    public RoomDeviceAdapter(List<RoomDeviceDetailBean.RoomDeviceList.RoomDevice> devices, OnItemClickListener listener) {
        this.devices = devices;
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull DeviceViewHolder holder, int position) {
        RoomDeviceDetailBean.RoomDeviceList.RoomDevice device = devices.get(position);
        if (!TextUtils.isEmpty(device.name)) {
            holder.deviceName.setText(device.name);
        }
        if (device.icon != null) {
            Glide.with(holder.deviceIcon.getContext())
                    .load(Url.BASE_URL + device.icon)
                    .error(Glide.with(holder.deviceIcon.getContext()).load(R.drawable.find_d))
                    .into(holder.deviceIcon);
        }
        holder.deviceadd.setOnClickListener(view -> {
            if (listener != null) {
                listener.onItemClick(device);
            }
        });
    }

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

    public interface OnItemClickListener {
        void onItemClick(RoomDeviceDetailBean.RoomDeviceList.RoomDevice device);
    }

    static class DeviceViewHolder extends RecyclerView.ViewHolder {
        ImageView deviceIcon;
        ImageView deviceadd;
        TextView deviceName;

        public DeviceViewHolder(@NonNull View itemView) {
            super(itemView);
            deviceIcon = itemView.findViewById(R.id.deviceIcon);
            deviceName = itemView.findViewById(R.id.deviceName);
            deviceadd = itemView.findViewById(R.id.deviceadd);
        }
    }
}