package xn.hxp.view.ble;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

import xn.hxp.databinding.ItemBleBinding;

public class BleScanAdapter extends BaseAdapter {
    private Context context;
    private List<BluetoothDevice> deviceList;

    public BleScanAdapter(Context context, List<BluetoothDevice> deviceList) {
        this.context = context;
        this.deviceList = deviceList;
    }

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

    @Override
    public BluetoothDevice getItem(int position) {
        return deviceList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            ItemBleBinding binding = ItemBleBinding.inflate(LayoutInflater.from(context), parent, false);
            convertView = binding.getRoot();
            viewHolder = new ViewHolder(binding);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        BluetoothDevice bleDevice = getItem(position);
        if (null != bleDevice) {
            String mac = bleDevice.getAddress();
            @SuppressLint("MissingPermission") String name = bleDevice.getName();
            viewHolder.binding.bleMac.setText(TextUtils.isEmpty(mac) ? "" : mac);
            viewHolder.binding.bleName.setText(TextUtils.isEmpty(name) ? "" : name);
        }
        return convertView;
    }

    static class ViewHolder {
        ItemBleBinding binding;

        public ViewHolder(ItemBleBinding binding) {
            this.binding = binding;
        }
    }
}
