#!/usr/bin/python3
#|----------------------------------------------------------------------------|#
#| Project: Generative Sountrack Music for Video Games.
#| Script: soundtrack_generator.py
#| Description: Generate base music playing tracks randomly with this script. 
#|    Part of a toolkit for generative audio.
#| Event: XGNR 2023
#| Author: 4lf0n (clan chiwire) <siempregaming@proton.me>
#| License: AGPLv3
#|----------------------------------------------------------------------------|#
# Modules.
import pygame
import pygame.mixer_music
import random
import time
from melody_generator import MelodyGenerator
from effects_generator import EffectsGenerator

# Class.
class GenerativeSoundtrack:
    # Init.
    def __init__(self,total_time=180):
        pygame.mixer.init()
        self.bpm = 120
        self.base_tracks = []
        self.effects_sounds = []
        self.melody_sounds = []
        self.total_time = total_time


    # Load base tracks.
    def load_base_tracks(self):
        self.base_tracks.append(pygame.mixer.Sound('Bases/jungle.ogg'))
        #self.base_tracks.append(pygame.mixer.Sound('Bases/CHANGEME.ogg'))
        # Loop base.
        #self.base_tracks[0].play(loops=-1, maxtime=20)


    # Choice base track
    def choice_base_track(self):
        base_track = random.choice(self.base_tracks)
        base_track.play()


    # Effects.
    def effects(self):
        # Genera la melodía
        generator = EffectsGenerator()
        generator.generate_effects(num_effects=20)


    # Melodies.
    def melodies(self):
        melody_sound = MelodyGenerator()
        melody_sound.generate_melodies(num_tones=25)

    # Run.
    def run(self):
        pygame.mixer.set_num_channels(3)
        self.load_base_tracks()
        pygame.init()
        clock = pygame.time.Clock()
        initial_time = time.time()
        while (time.time() - initial_time) < self.total_time:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    return

            # Llama a los métodos de generación de música
            self.choice_base_track()
            self.melodies()
            self.effects()
            clock.tick(self.bpm)


# Main.
if __name__ == "__main__":
    soundtrack = GenerativeSoundtrack(total_time=180)
    soundtrack.run()
