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

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

import _thread
import importlib
import os

import pyperclip

from fenrirscreenreader.core.i18n import _


class command:
    def __init__(self):
        pass

    def initialize(self, environment, script_path=""):
        self.env = environment
        self.script_path = script_path

    def shutdown(self):
        pass

    def get_description(self):
        return _("imports the graphical clipboard to Fenrir's clipboard")

    def run(self):
        _thread.start_new_thread(self._thread_run, ())

    def _thread_run(self):
        try:
            # Remember original display environment variable if it exists
            original_display = os.environ.get("DISPLAY", "")
            clipboard_content = None

            # Try different display options
            for i in range(10):
                display = f":{i}"
                try:
                    # Set display environment variable
                    os.environ["DISPLAY"] = display
                    # Attempt to get clipboard content
                    # Weird workaround for some distros
                    importlib.reload(pyperclip)
                    clipboard_content = pyperclip.paste()
                    # If we get here without exception, we found a working
                    # display
                    if clipboard_content:
                        break
                except Exception:
                    # Failed for this display, try next one
                    continue

            # Restore original display setting
            if original_display:
                os.environ["DISPLAY"] = original_display
            else:
                os.environ.pop("DISPLAY", None)

            # Process the clipboard content if we found any
            if clipboard_content and isinstance(clipboard_content, str):
                self.env["runtime"]["MemoryManager"].add_value_to_first_index(
                    "clipboardHistory", clipboard_content
                )
                self.env["runtime"]["OutputManager"].present_text(
                    "Import to Clipboard",
                    sound_icon="CopyToClipboard",
                    interrupt=True,
                )
                self.env["runtime"]["OutputManager"].present_text(
                    clipboard_content, sound_icon="", interrupt=False
                )
            else:
                self.env["runtime"]["OutputManager"].present_text(
                    "No text found in clipboard or no accessible display",
                    interrupt=True,
                )
        except Exception as e:
            self.env["runtime"]["OutputManager"].present_text(
                str(e), sound_icon="", interrupt=False
            )

    def set_callback(self, callback):
        pass
