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

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

import _thread
import os
from subprocess import PIPE
from subprocess import Popen

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 _("script: {0} fullpath: {1}").format(
            os.path.basename(self.script_path), self.script_path
        )

    def run(self):
        if not os.path.exists(self.script_path):
            self.env["runtime"]["OutputManager"].present_text(
                _("Script file not found"), sound_icon="", interrupt=False
            )
            return
        if not os.path.isfile(self.script_path):
            self.env["runtime"]["OutputManager"].present_text(
                _("Script source is not a valid file"),
                sound_icon="",
                interrupt=False,
            )
            return
        if not os.access(self.script_path, os.X_OK):
            self.env["runtime"]["OutputManager"].present_text(
                _("Script file is not executable"),
                sound_icon="",
                interrupt=False,
            )
            return
        _thread.start_new_thread(self._thread_run, ())

    def _thread_run(self):
        try:
            p = Popen(
                [self.script_path, self.env["general"]["curr_user"]],
                stdout=PIPE,
                stderr=PIPE,
            )
            stdout, stderr = p.communicate()
            stdout = stdout.decode("utf-8")
            stderr = stderr.decode("utf-8")
            self.env["runtime"]["OutputManager"].interrupt_output()
            if stderr != "":
                self.env["runtime"]["OutputManager"].present_text(
                    str(stderr), sound_icon="", interrupt=False
                )
            if stdout != "":
                self.env["runtime"]["OutputManager"].present_text(
                    str(stdout), sound_icon="", interrupt=False
                )
        except Exception as e:
            self.env["runtime"]["OutputManager"].present_text(
                str(e), sound_icon="", interrupt=False
            )

    def set_callback(self, callback):
        pass
