package ai.pai.lensman.printer;

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;

import ai.pai.lensman.R;
import ai.pai.lensman.db.Preferences;

/**
 * Created by chengzhenyu on 2016/9/1.
 */

public class BluetoothDeviceListAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private ArrayList<BluetoothDevice> deviceList;

    public BluetoothDeviceListAdapter(Context context){
        inflater = LayoutInflater.from(context);
    }

    public void setDeviceList(ArrayList<BluetoothDevice> newDeviceList){
        this.deviceList = newDeviceList;
        notifyDataSetChanged();
    }

    public ArrayList<BluetoothDevice> getDeviceList(){
        return deviceList;
    }

    public void addDevice(BluetoothDevice device){
        if(this.deviceList==null){
            this.deviceList = new ArrayList<>();
        }
        if(!this.deviceList.contains(device)){
            this.deviceList.add(device);
        }
        notifyDataSetChanged();
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder;
        if(convertView==null){
            convertView = inflater.inflate(R.layout.layout_bt_device_list_item,viewGroup,false);
            holder = new ViewHolder();
            holder.deviceMac =(TextView) convertView.findViewById(R.id.tv_device_mac);
            holder.deviceName =(TextView) convertView.findViewById(R.id.tv_device_name);
            holder.deviceStatus =(TextView) convertView.findViewById(R.id.tv_device_status);
            convertView.setTag(holder);
        }else{
            holder  = (ViewHolder) convertView.getTag();
        }
        BluetoothDevice device = deviceList.get(position);
        holder.deviceName.setText(device.getName());
        holder.deviceMac.setText(device.getAddress());
        if(device.getAddress().equals(Preferences.getInstance().getPrinterMac())){
            holder.deviceStatus.setText(R.string.click_to_connect);
        }else{
            holder.deviceStatus.setText("");
        }
        return convertView;
    }

    public static class ViewHolder{

        public TextView deviceName;
        public TextView deviceMac;
        public TextView deviceStatus;
    }
}
