import PyQt5.QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeyEvent

class KeyboardNotifier:
    def __init__(self):
        # keyboard shortcuts
        self.key_dict = {
            "track": Qt.Key_E,
            "play_pause": Qt.Key_Space,
            # azerty vs qwerty
            "left": ([Qt.Key_Left, Qt.Key_Q], [Qt.Key_Left, Qt.Key_A])[PyQt5.QtCore.QLocale().language() == PyQt5.QtCore.QLocale().French],
            "right": [Qt.Key_Right, Qt.Key_D],
            "numbers": [Qt.Key_0, Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4, Qt.Key_5, Qt.Key_6, Qt.Key_7, Qt.Key_8, Qt.Key_9],
            "jump": Qt.Key_J
        }
        self.listeners = set()

    def keyPressEvent(self, event):
        if type(event) != QKeyEvent:
            event.ignore()

        if event.key() == self.key_dict["play_pause"]:
            self.notify_listeners("on_key_play_pause")

        if event.key() in self.key_dict["left"]:
            self.notify_listeners("on_key_left", event.modifiers())

        if event.key() in self.key_dict["right"]:
            self.notify_listeners("on_key_right", event.modifiers())

        if event.key() == Qt.Key_Control:
            self.notify_listeners("on_key_ctrl", True)

        if event.key() == Qt.Key_Delete:
            self.notify_listeners("on_key_delete")

        if event.key() in self.key_dict["numbers"]:
            self.notify_listeners("on_key_number", self.key_dict["numbers"].index(event.key()))

        if event.key() in [Qt.Key_W, Qt.Key_S]:
            self.notify_listeners("on_key_ws", event.key() == Qt.Key_W)

        if event.key() == self.key_dict["track"]:
            self.notify_listeners("on_key_track", False)

        if event.key() == self.key_dict["jump"]:
            self.notify_listeners("on_key_jump", event.modifiers())

    def keyReleaseEvent(self, event):
          if event.key() == Qt.Key_Control:
            self.notify_listeners("on_key_ctrl", False)

    def add_listener(self, listener):
        self.listeners.add(listener)

    def add_listeners(self, *listeners):
        self.listeners.update(listeners)

    def auto_track(self):
        self.notify_listeners("on_key_track", True)

    def notify_listeners(self, method_name, *args):
        for listener in self.listeners:
            func = getattr(listener, method_name)
            func(*args)


class KeyboardListener:
    def on_key_play_pause(self):
        pass

    def on_key_ctrl(self, holding):
        pass

    def on_key_left(self, modifiers):
        pass

    def on_key_right(self, modifiers):
        pass

    def on_key_delete(self):
        pass

    def on_key_number(self, number):
        pass

    def on_key_ws(self, go_up):
        pass

    def on_key_track(self, automatic):
        pass

    def on_key_jump(self, modifiers):
        pass