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

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

import os

from fenrirscreenreader.core import debug
from fenrirscreenreader.core.i18n import _


class command:
    def __init__(self):
        pass

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

    def shutdown(self):
        pass

    def get_description(self):
        return _("export the current fenrir clipboard to a file")

    def run(self):
        clipboard_file_path = self.env["runtime"][
            "SettingsManager"
        ].get_setting("general", "clipboard_export_path")
        clipboard_file_path = clipboard_file_path.replace(
            "$user", self.env["general"]["curr_user"]
        )
        clipboard_file_path = clipboard_file_path.replace(
            "$USER", self.env["general"]["curr_user"]
        )
        clipboard_file_path = clipboard_file_path.replace(
            "$User", self.env["general"]["curr_user"]
        )
        clipboard_file = open(clipboard_file_path, "w")
        try:
            if self.env["runtime"]["MemoryManager"].is_index_list_empty(
                "clipboardHistory"
            ):
                self.env["runtime"]["OutputManager"].present_text(
                    _("clipboard empty"), interrupt=True
                )
                return
            clipboard = self.env["runtime"][
                "MemoryManager"
            ].get_index_list_element("clipboardHistory")
            clipboard_file.write(clipboard)
            clipboard_file.close()
            os.chmod(clipboard_file_path, 0o644)
            self.env["runtime"]["OutputManager"].present_text(
                _("clipboard exported to file"), interrupt=True
            )
        except Exception as e:
            self.env["runtime"]["DebugManager"].write_debug_out(
                "export_clipboard_to_file:run: Filepath:"
                + clipboard_file
                + " trace:"
                + str(e),
                debug.DebugLevel.ERROR,
            )

    def set_callback(self, callback):
        pass
