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

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

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


class command:
    def __init__(self):
        pass

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

    def shutdown(self):
        pass

    def get_description(self):
        return _("Read all text page by page from current position")

    def run(self):
        # Check if speechd is available for callbacks
        try:
            speech_driver = self.env['runtime']['SpeechDriver']
            if not (hasattr(speech_driver, '_sd') and speech_driver._sd):
                self.env["runtime"]["OutputManager"].present_text(
                    _("Read all requires speech-dispatcher - not available with current speech driver"),
                    interrupt=True
                )
                return
        except Exception as e:
            self.env["runtime"]["DebugManager"].write_debug_out(
                f"ReadAllByPage run: Error checking speech driver: {e}",
                debug.DebugLevel.ERROR
            )
            return
        
        # Check if ReadAllManager is available
        if "ReadAllManager" not in self.env["runtime"]:
            self.env["runtime"]["OutputManager"].present_text(
                _("Read all manager not in runtime"),
                interrupt=True
            )
            return
        elif not self.env["runtime"]["ReadAllManager"]:
            self.env["runtime"]["OutputManager"].present_text(
                _("Read all manager is None"),
                interrupt=True
            )
            return
        
        # Start continuous page-by-page reading
        if self.env["runtime"]["ReadAllManager"].is_active():
            # Stop if already active
            self.env["runtime"]["ReadAllManager"].stop_read_all()
        else:
            # Start page-by-page reading
            self.env["runtime"]["ReadAllManager"].start_read_all('page')


    def set_callback(self, callback):
        pass
