package xn.hxp.weidith.ble;

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 com.clj.fastble.data.BleDevice;

import java.util.List;

import xn.hxp.databinding.ItemBleBinding;

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

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

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

    @Override
    public BleDevice 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();
        }
        BleDevice bleDevice = getItem(position);
        if (null != bleDevice) {
            String mac = bleDevice.getMac();
            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;
        }
    }
}
