package com.common.bluetooth.view;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.common.bluetooth.databinding.RvBtDeviceItemBinding;

import java.util.ArrayList;

/**
 * 连接设备列表
 *
 * @author wangym
 * @since 2021-11-2
 */
public class BtDeviceListAdapter extends RecyclerView.Adapter<BtDeviceListAdapter.BtViewHolder> {
    private static final String TAG = "BtDeviceListAdapter";
    private Context context;
    private ArrayList<BluetoothDevice> bluetoothDevices;
    private RvBtDeviceItemBinding mBinding;
    private OnDeviceClickListener onDeviceClickListener;

    public BtDeviceListAdapter(Context context, ArrayList<BluetoothDevice> bluetoothDevices) {
        this.context = context;
        this.bluetoothDevices = bluetoothDevices;
    }

    @NonNull
    @Override
    public BtViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        mBinding = RvBtDeviceItemBinding.inflate(LayoutInflater.from(context));
        return new BtViewHolder(mBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull BtViewHolder holder, int position) {
        final int currentIndex = position;
        BluetoothDevice device = bluetoothDevices.get(position);
        holder.binding.btDeviceNameTv.setText("Device Name:" + device.getName());
        holder.binding.btDeviceMacTv.setText("Device MAC:" + device.getAddress());
        holder.binding.btDeviceItemRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onDeviceClickListener != null) {
                    onDeviceClickListener.onClick(currentIndex);
                }
            }
        });
    }

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

    protected static class BtViewHolder extends RecyclerView.ViewHolder {
        public RvBtDeviceItemBinding binding;

        public BtViewHolder(@NonNull RvBtDeviceItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    public void setOnDeviceClickListener(OnDeviceClickListener onDeviceClickListener) {
        this.onDeviceClickListener = onDeviceClickListener;
    }

    public interface OnDeviceClickListener {
        void onClick(int index);
    }
}
