"""Configuration management module for PygStormGames.

Handles loading and saving of both local and global game configurations.
"""

import os
import configparser
from xdg import BaseDirectory

class Config:
    """Handles configuration file management."""
    
    def __init__(self, gameTitle):
        """Initialize configuration system.
        
        Args:
            gameTitle (str): Title of the game
        """
        # Set up config parsers
        self.localConfig = configparser.ConfigParser()
        self.globalConfig = configparser.ConfigParser()
        
        # Set up paths
        self.globalPath = os.path.join(BaseDirectory.xdg_config_home, "storm-games")
        gameDir = str.lower(str.replace(gameTitle, " ", "-"))
        self.gamePath = os.path.join(self.globalPath, gameDir)
        
        # Create directories if needed
        if not os.path.exists(self.gamePath):
            os.makedirs(self.gamePath)
            
        # Full paths to config files
        self.localConfigPath = os.path.join(self.gamePath, "config.ini")
        self.globalConfigPath = os.path.join(self.globalPath, "config.ini")
        
        # Load initial configurations
        self.read_config()
        self.read_config(globalConfig=True)
        
    def read_config(self, globalConfig=False):
        """Read configuration from file.
        
        Args:
            globalConfig (bool): If True, read global config, otherwise local
        """
        config = self.globalConfig if globalConfig else self.localConfig
        path = self.globalConfigPath if globalConfig else self.localConfigPath
        
        try:
            with open(path, 'r') as configfile:
                config.read_file(configfile)
        except FileNotFoundError:
            # It's okay if the file doesn't exist yet
            pass
        except Exception as e:
            print(f"Error reading {'global' if globalConfig else 'local'} config: {e}")
            
    def write_config(self, globalConfig=False):
        """Write configuration to file.
        
        Args:
            globalConfig (bool): If True, write to global config, otherwise local
        """
        config = self.globalConfig if globalConfig else self.localConfig
        path = self.globalConfigPath if globalConfig else self.localConfigPath
        
        try:
            with open(path, 'w') as configfile:
                config.write(configfile)
        except Exception as e:
            print(f"Error writing {'global' if globalConfig else 'local'} config: {e}")
            
    def get_value(self, section, key, default=None, globalConfig=False):
        """Get value from configuration.
        
        Args:
            section (str): Configuration section
            key (str): Configuration key
            default: Default value if not found
            globalConfig (bool): If True, read from global config
            
        Returns:
            Value from config or default if not found
        """
        config = self.globalConfig if globalConfig else self.localConfig
        try:
            return config.get(section, key)
        except:
            return default
            
    def set_value(self, section, key, value, globalConfig=False):
        """Set value in configuration.
        
        Args:
            section (str): Configuration section
            key (str): Configuration key
            value: Value to set
            globalConfig (bool): If True, write to global config
        """
        config = self.globalConfig if globalConfig else self.localConfig
        
        # Create section if it doesn't exist
        if not config.has_section(section):
            config.add_section(section)
            
        config.set(section, key, str(value))
        self.write_config(globalConfig)
        
    def get_int(self, section, key, default=0, globalConfig=False):
        """Get integer value from configuration.
        
        Args:
            section (str): Configuration section
            key (str): Configuration key
            default (int): Default value if not found
            globalConfig (bool): If True, read from global config
            
        Returns:
            int: Value from config or default if not found
        """
        try:
            return int(self.get_value(section, key, default, globalConfig))
        except:
            return default
            
    def get_float(self, section, key, default=0.0, globalConfig=False):
        """Get float value from configuration.
        
        Args:
            section (str): Configuration section
            key (str): Configuration key
            default (float): Default value if not found
            globalConfig (bool): If True, read from global config
            
        Returns:
            float: Value from config or default if not found
        """
        try:
            return float(self.get_value(section, key, default, globalConfig))
        except:
            return default
            
    def get_bool(self, section, key, default=False, globalConfig=False):
        """Get boolean value from configuration.
        
        Args:
            section (str): Configuration section
            key (str): Configuration key
            default (bool): Default value if not found
            globalConfig (bool): If True, read from global config
            
        Returns:
            bool: Value from config or default if not found
        """
        try:
            return self.get_value(section, key, default, globalConfig).lower() in ['true', '1', 'yes', 'on']
        except:
            return default