#!/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 _("Export current fenrir clipboard to X or GUI clipboard")

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

    def _thread_run(self):
        try:
            # Check if clipboard is empty
            if self.env["runtime"]["MemoryManager"].is_index_list_empty(
                "clipboardHistory"
            ):
                self.env["runtime"]["OutputManager"].present_text(
                    _("clipboard empty"), interrupt=True
                )
                return

            # Get current clipboard content
            clipboard = self.env["runtime"][
                "MemoryManager"
            ].get_index_list_element("clipboardHistory")

            # Remember original display environment variable if it exists
            original_display = os.environ.get("DISPLAY", "")
            success = False

            # Try different display options
            for i in range(10):
                display = f":{i}"
                try:
                    # Set display environment variable
                    os.environ["DISPLAY"] = display
                    # Attempt to set clipboard content
                    # Weird workaround for some distros
                    importlib.reload(pyperclip)
                    pyperclip.copy(clipboard)
                    # If we get here without exception, we found a working
                    # display
                    success = True
                    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)

            # Notify the user of the result
            if success:
                self.env["runtime"]["OutputManager"].present_text(
                    _("exported to the X session."), interrupt=True
                )
            else:
                self.env["runtime"]["OutputManager"].present_text(
                    _(
                        "failed to export to X clipboard. No available display "
                        "found."
                    ),
                    interrupt=True,
                )

        except Exception as e:
            self.env["runtime"]["OutputManager"].present_text(
                str(e), sound_icon="", interrupt=False
            )

    def set_callback(self, callback):
        pass
