package com.gto.bt_sample_code;

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

import java.util.ArrayList;

public class BleAdatper extends BaseAdapter {


    private Context mCotext;
    private ArrayList<BluetoothDevice> mLeDevices;

    public BleAdatper(Context mCotext) {
        this.mCotext = mCotext;
        mLeDevices = new ArrayList<BluetoothDevice>();
    }

    @Override
    public int getCount() {
        return mLeDevices.size();
    }

    @Override
    public Object getItem(int i) {
        return mLeDevices.get(i);
    }

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


    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder; // view lookup cache stored in tag
        if (view == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(mCotext);
            view = inflater.inflate(R.layout.bt_item, viewGroup, false);
            viewHolder.mPrinter = view.findViewById(R.id.bt_item_name);
            viewHolder.mMac=view.findViewById(R.id.bt_item_mac);
            view.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) view.getTag();

        }

        if (mLeDevices.size() != 0) {
            BluetoothDevice device = mLeDevices.get(i);
            final String deviceName = device.getName();
            if (deviceName != null && deviceName.length() > 0) {
                viewHolder.mPrinter.setText(device.getName());
                viewHolder.mMac.setText(device.getAddress());
            } else {
                viewHolder.mPrinter.setText("Unknown device.");
            }

        }

        return view;
    }


    class ViewHolder {
        TextView mPrinter;
        TextView mMac;
    }

//    public void setConnectedDevice() {
//        viewHolderDrop.mPrinter.setText("已連線裝置");
//    }

    public void addDevice(BluetoothDevice device) {
        if (device.getName() != null) {
            if (!mLeDevices.contains(device) ) {
                mLeDevices.add(device);
            }
        }
    }

    public BluetoothDevice getDevice(int position) {
        if (mLeDevices.size() == 0) {
            return null;
        } else {
            return mLeDevices.get(position);
        }

    }

}
