#!/usr/bin/env python3

from fenrirscreenreader.core.i18n import _


class command:
    def __init__(self):
        pass

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

    def shutdown(self):
        pass

    def get_description(self):
        return "Discard temporary changes and revert to saved settings"

    def run(self):
        self.env["runtime"]["OutputManager"].present_text(
            "Reverting to saved configuration...", interrupt=True
        )

        try:
            # Reload settings from file, discarding runtime changes
            SettingsManager = self.env["runtime"]["SettingsManager"]
            SettingsManager.load_settings()

            # Reinitialize speech system with restored settings
            if "SpeechDriver" in self.env["runtime"]:
                try:
                    SpeechDriver = self.env["runtime"]["SpeechDriver"]
                    SpeechDriver.shutdown()
                    SpeechDriver.initialize(self.env)
                except Exception as e:
                    print(
                        f"revert_to_saved SpeechDriver: Error reinitializing speech driver: {str(e)}"
                    )

            # Reinitialize sound system with restored settings
            if "sound_driver" in self.env["runtime"]:
                try:
                    sound_driver = self.env["runtime"]["sound_driver"]
                    sound_driver.shutdown()
                    sound_driver.initialize(self.env)
                except Exception as e:
                    print(
                        f"revert_to_saved sound_driver: Error reinitializing sound driver: {str(e)}"
                    )

            self.env["runtime"]["OutputManager"].present_text(
                "Successfully reverted to saved settings",
                interrupt=False,
                flush=False,
            )
            self.env["runtime"]["OutputManager"].present_text(
                "All temporary changes have been discarded",
                interrupt=False,
                flush=False,
            )

        except Exception as e:
            self.env["runtime"]["OutputManager"].present_text(
                f"Error reverting settings: {str(e)}",
                interrupt=False,
                flush=False,
            )
            self.env["runtime"]["OutputManager"].present_text(
                "You may need to restart Fenrir", interrupt=False, flush=False
            )

    def set_callback(self, callback):
        pass
