from glob import glob

# from subprocess import check_output, CalledProcessError
import platform

# import os
import psutil
import time
from usbmonitor import USBMonitor
from usbmonitor.attributes import ID_MODEL, ID_MODEL_ID, ID_VENDOR_ID, DEVNAME


class ObjectWithEvents(object):
    callbacks = None
    
    def on(self, event_name, callback):
        print('calling ON')
        if self.callbacks is None:
            self.callbacks = {}

        if event_name not in self.callbacks:
            self.callbacks[event_name] = [callback]
        else:
            self.callbacks[event_name].append(callback)

    def trigger(self, event_name):
        print('calling TRIGGER')
        if self.callbacks is not None and event_name in self.callbacks:
            for callback in self.callbacks[event_name]:
                callback(self)


class USBDeviceHandler(ObjectWithEvents):
    def __init__(self):
        print("init USB handler")
        self.monitor = USBMonitor()
        self.startUSBmonitor()

    def startUSBmonitor(self):
        print(self.get_usb_devices())
        self.monitor.start_monitoring(self.on_connect, self.on_disconnect)

    def stopUSBmonitor(self):
        self.monitor.stop_monitoring()

    def device_info_str(self, device_info):
        return f"{device_info[ID_MODEL]} ({device_info[ID_MODEL_ID]} - {device_info[ID_VENDOR_ID]}) at {device_info[DEVNAME]}"

    def on_connect(self, device_id, device_info):
        print("Connected: " + self.device_info_str(device_info=device_info))
        print(self.get_usb_devices())
        self.trigger('example_event')

    def on_disconnect(self, device_id, device_info):
        print("Disconnected: " + self.device_info_str(device_info=device_info))
        print(self.get_usb_devices())
        self.trigger('example_event')

    def get_usb_devices(self):
        # delay the reading for 1 second, i guess until it is mounted as partition?
        time.sleep(2)
        current_os = platform.system()
        print(current_os)

        disks = psutil.disk_partitions()
        # MacOS
        if current_os == "Darwin":
            os_drive_path = "/Volumes"
            """os.chdir("/Volumes")
            # then do some listing
            List = os.listdir()
            i = 0
            while i < len(List):
                if List[i] == "Macintosh HD" or List[i] == "Recovery":
                    del List[i : i + 1]
                    continue
                else:
                    List[i] = "/Volumes/" + List[i]
                    i += 1

            return List"""

        # Linux
        elif current_os == "Linux":
            os_drive_path = ""
            """def get_linux_usb_devices():
                sdb_devices = map(os.path.realpath, glob("/sys/block/sd*"))
                usb_devices = (dev for dev in sdb_devices if "usb" in dev.split("/")[5])
                return dict((os.path.basename(dev), dev) for dev in usb_devices)

            devices = get_linux_usb_devices()
            output = check_output(["mount"]).splitlines()
            is_usb = lambda path: any(dev in path for dev in devices)
            usb_info = (line for line in output if is_usb(line.split()[0]))
            return [(info.split()[0], info.split()[2]) for info in usb_info]
            """
        usb_disks = []
        for disk in disks:
            if (os_drive_path in disk.mountpoint) and (disk.fstype == "exfat"):
                usb_disks.append(disk)

        
        return usb_disks
