package com.example.myapplication.util;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class USBDevDiscoverHelper
{
    private Context mContext;
    private UsbManager mUsbManager;

    private List<UsbDevice> mUsbDevList;

    private String LOG_TAG;

    public USBDevDiscoverHelper(@NonNull Context context)
    {
        this.mContext = context;
        this.mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        this.mUsbDevList = new ArrayList<>();
        this.LOG_TAG = this.getClass().getSimpleName();
    }

    /**
     * discover
     * Discover the USB devices that are connected to host
     * @param       None
     * @exception   None
     * @return      None
     */
    public void discover()
    {
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();      //Obtain a list of USB devices from interface
        Iterator<UsbDevice> deviceListIterator = deviceList.values().iterator();

        this.mUsbDevList.clear();
        //Do not proceed if there is no device found
        if (deviceList.isEmpty())
        {
            Log.e(LOG_TAG, "There is no USB device attached.");
            return;
        }

        while(deviceListIterator.hasNext())
        {
            UsbDevice device = deviceListIterator.next();
            mUsbDevList.add(device);
        }
    }


    public void release()
    {
        this.mUsbManager.getDeviceList().clear();
        this.mUsbDevList.clear();
    }
    /**
     * getUsbDevList
     * Return a list of USB devices
     * @param       None
     * @exception   None
     * @return      None
     */
    public List getUsbDevList()
    {
        return this.mUsbDevList;
    }

    /**
     * getUsbDevListToString
     * Return a String that contains the details of the USB devices in the list
     * @param       None
     * @exception   None
     * @return      String - contains the details of the USB devices in the list
     */
    public String getUsbDevListToString()
    {
        StringBuilder strBlder = new StringBuilder();
        for (int i = 0; i < this.mUsbDevList.size() ; ++i)
        {
            strBlder.append("====================");
            strBlder.append("===== Device "+i+1+" =====");
            strBlder.append(this.mUsbDevList.get(i).getVendorId()+"\n");
            strBlder.append(this.mUsbDevList.get(i).getProductId()+"\n");
            strBlder.append(this.mUsbDevList.get(i).getDeviceName()+"\n");
            strBlder.append(this.mUsbDevList.get(i).getDeviceId()+"\n");
            strBlder.append("====================");
        }
        return strBlder.toString();
    }
}
