# -*- encoding: utf-8 -*-

import re
import subprocess
import sys
import os
import logging


class Hardware(object):
    """
    Inspect system for supported via USB connected devices.

    Currently supportd devices:
        * HackRF One
        * rad1o
        * LTR-SDR DVB-T stick
    """
    SUPPORTED_HARDWARE = {
        "hackrfone": "1d50:cc15",  # rad1o and hackrf one has the same id :/
        "rtlsdr": "0bda:2838"      # Realtek Semiconductor Corp. RTL2838 DVB-T
    }

    @staticmethod
    def get_usb_devices():
        """
        Parse lsusb output and return a list of dictionaries.
        """
        devices = []

        lsusb_output = subprocess.check_output("lsusb", shell=True)
        for line in lsusb_output.split("\n"):
            if re.match("^Bus", line):
                device = Hardware.parse_lsusb_line(line)
                devices.append(device)
            else:
                continue

        return devices

    @staticmethod
    def get_connected_supported_devices():
        """
        Get all connected devices
        """
        devices = Hardware.get_usb_devices()

        connected_devices = []
        for device in devices:
            if Hardware.supported_device(device):
                connected_devices.append(device)
            else:
                continue

        return connected_devices

    @staticmethod
    def parse_lsusb_line(line):
        """
        Splitt lsusb line in useful key values.
        """
        device = {}
        device_unsorted = line.split(" ")

        device['bus'] = device_unsorted[1]
        device['device'] = re.match(r"(?P<id>\d+)", device_unsorted[3]).group()
        device['id'] = device_unsorted[5]
        device['name'] = " ".join(device_unsorted[6:])

        return device

    @staticmethod
    def supported_device(device):
        """
        Check if a given device is supported.
        """
        return device['id'] in Hardware.SUPPORTED_HARDWARE.values()