import pygame
from client.resource_path import get_asset_path

class AudioManager:
    def __init__(self):
        pygame.mixer.init()
        self.current_track = None
        self.is_playing = False
        self.music_tracks = {
            "background_menu": "client/assets/sounds/music/The Fall of Arcana.mp3"
        }
        self.sounds = {}

    # Music
    def get_music_position(self):
        # Returns milliseconds
        return pygame.mixer.music.get_pos()

    def resume_music(self, name, loops=-1):
        pos = self.get_music_position()
        self.play_music(name, loops=loops, start_pos=pos / 1000.0)

    def is_music_playing(self):
        return pygame.mixer.music.get_busy()
    
    def set_music_volume(self, volume):
        pygame.mixer.music.set_volume(volume)  # volume: 0.0 to 1.0

    def get_music_volume(self):
        return pygame.mixer.music.get_volume()
    
    def add_music(self, name, file_path):
        self.music_tracks[name] = file_path

    def play_music(self, name, loops=-1, start_pos=0.0):
        file_path = self.music_tracks.get(name, name)  # Allow direct path or name
        # Convert to absolute path for PyInstaller
        if file_path.startswith('client/assets/'):
            absolute_path = get_asset_path(file_path.replace('client/assets/', ''))
        else:
            absolute_path = file_path
        
        if self.current_track != file_path or not self.is_playing:
            pygame.mixer.music.load(absolute_path)
            pygame.mixer.music.play(loops=loops, start=start_pos)
            self.current_track = file_path
            self.is_playing = True

    def stop_music(self):
        pygame.mixer.music.stop()
        self.is_playing = False

    def pause_music(self):
        pygame.mixer.music.pause()

    def unpause_music(self):
        pygame.mixer.music.unpause()
    
    # Sound Effects
    def add_sound(self, name, file_path):
        # Convert to absolute path for PyInstaller
        if file_path.startswith('client/assets/'):
            absolute_path = get_asset_path(file_path.replace('client/assets/', ''))
        else:
            absolute_path = file_path
        self.sounds[name] = pygame.mixer.Sound(absolute_path)

    def play_sound(self, name):
        if name in self.sounds:
            self.sounds[name].play()
        else:
            print(f"Sound effect '{name}' not found.")

    def set_sound_volume(self, volume):
        for sound in self.sounds.values():
            sound.set_volume(volume)  # volume: 0.0 to 1.0
    
    def get_sound_volume(self):
        return pygame.mixer.sound.get_volume()