#!/usr/bin/env python3

import importlib.util
import os

from fenrirscreenreader.core.i18n import _

# Load base configuration class
_base_path = os.path.join(os.path.dirname(__file__), "..", "config_base.py")
_spec = importlib.util.spec_from_file_location("config_base", _base_path)
_module = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_module)
config_command = _module.config_command


class command(config_command):
    def __init__(self):
        super().__init__()

    def get_description(self):
        return "Select sound theme"

    def run(self):
        current_theme = self.get_setting("sound", "theme", "default")
        current_theme_name = os.path.basename(
            os.path.normpath(current_theme)
        )

        # Present current theme
        self.present_text(f"Current sound theme: {current_theme}")

        # Look for available sound themes
        sound_paths = self.env[
            "runtime"
        ]["SettingsManager"].get_sound_theme_roots()

        available_themes = self.get_available_themes(sound_paths)

        if len(available_themes) > 1:
            # For this implementation, cycle through available themes
            try:
                current_index = available_themes.index(current_theme_name)
                next_index = (current_index + 1) % len(available_themes)
                new_theme = available_themes[next_index]
            except ValueError:
                # Current theme not found in available themes, use first one
                new_theme = available_themes[0]

            success = self.set_setting("sound", "theme", new_theme)

            if success:
                self.present_text(f"Sound theme changed to: {new_theme}")
                self.play_sound("Accept")
            else:
                self.present_text("Failed to change sound theme")
                self.play_sound("Error")
        else:
            self.present_text("Only default sound theme is available")
            self.play_sound("Cancel")

    def get_available_themes(self, searchPaths):
        """Find available sound themes in the search paths"""
        themes = ["default"]  # Always include default

        for path in searchPaths:
            if os.path.isdir(path):
                try:
                    for item in os.listdir(path):
                        full_path = os.path.join(path, item)
                        if (
                            os.path.isdir(full_path)
                            and item != "default"
                            and item not in themes
                        ):
                            # Check if it looks like a sound theme (contains
                            # sound files)
                            if self.is_valid_sound_theme(full_path):
                                themes.append(item)
                except Exception:
                    continue

        return themes

    def is_valid_sound_theme(self, themePath):
        """Check if a directory contains sound files"""
        sound_extensions = [".wav", ".ogg", ".mp3", ".flac"]
        try:
            for file in os.listdir(themePath):
                if any(file.lower().endswith(ext) for ext in sound_extensions):
                    return True
        except Exception:
            pass
        return False
