#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributors.

import time

from fenrirscreenreader.core import debug


class InputDriver:
    def __init__(self):
        self._initialized = False

    def initialize(self, environment):
        self.env = environment
        self._is_initialized = True

    def shutdown(self):
        if self._initialized:
            self.remove_all_devices()
        self._is_initialized = False

    def get_input_event(self):
        time.sleep(0.1)
        return None

    def clear_event_buffer(self):
        if not self._initialized:
            return
        del self.env["input"]["event_buffer"][:]

    def update_input_devices(self, new_devices=None, init=False):
        if not self._initialized:
            return

    def get_led_state(self, led=0):
        if not self._initialized:
            return False
        return False

    def toggle_led_state(self, led=0):
        if not self._initialized:
            return

    def grab_all_devices(self):
        if not self._initialized:
            return True
        return True

    def ungrab_all_devices(self):
        if not self._initialized:
            return True
        return True

    def force_ungrab(self):
        """Emergency method to release grabbed devices in case of failure"""
        if not self._initialized:
            return True
        try:
            # Try standard ungrab first
            return self.ungrab_all_devices()
        except Exception as e:
            # Just log the failure and inform the user
            if (
                hasattr(self, "env")
                and "runtime" in self.env
                and "DebugManager" in self.env["runtime"]
            ):
                self.env["runtime"]["DebugManager"].write_debug_out(
                    f"Emergency device release failed: {str(e)}",
                    debug.DebugLevel.ERROR,
                )
            else:
                print(f"Emergency device release failed: {str(e)}")
        return False

    def has_i_devices(self):
        if not self._initialized:
            return False
        return True

    def remove_all_devices(self):
        if not self._initialized:
            return

    def send_key(self):
        if not self._initialized:
            return

    def __del__(self):
        if not self._initialized:
            return
        try:
            self.remove_all_devices()
        except Exception as e:
            print(f"InputDriver __del__: Error removing devices: {str(e)}")
