import msvcrt
import queue
import threading
import time

from .keyboard_abc import KeyboardABC


class KeyboardWindows(KeyboardABC):
    KEY_MAP = {
        'H': 'ArrowUp',
        'P': 'ArrowDown',
        'K': 'ArrowLeft',
        'M': 'ArrowRight',
        'G': 'Home',
        'O': 'End',
        'R': 'Insert',
        'S': 'Delete',
    }

    def __init__(self):
        self.queue = queue.Queue()
        self.running = False
        self.thread = None

    def _listener(self):
        while self.running:
            if msvcrt.kbhit():
                ch = msvcrt.getwch()
                if ch in ('\x00', '\xe0'):
                    ch2 = msvcrt.getwch()
                    self.queue.put(self.KEY_MAP.get(ch2, f"Unknown({ch2})"))
                elif ch == '\x1b':
                    self.queue.put("Escape")
                else:
                    self.queue.put(ch)
            else:
                time.sleep(0.01)

    def start(self):
        if self.running:
            return
        self.running = True
        self.thread = threading.Thread(target=self._listener, daemon=True)
        self.thread.start()

    def stop(self):
        self.running = False
        if self.thread:
            self.thread.join()
            self.thread = None

    def get_key(self):
        return self.queue.get()
