#shuvit.org
#mp3 player

import bge
import os
import aud
import random
import glob
from tinytag import TinyTag

# dict
dict = bge.logic.globalDict
dict['mu_current_song'] = ''
dict['mu_stopped'] = 1
dict['change_track'] = 0
dict['mu_track_time'] = 0

# create file path
directory = bge.logic.expandPath("//")
file_name = directory + "Music\\*.mp3" # Test directory "Test\\Music\\*.mp3"
file_list = glob.glob(file_name)
selected = random.choice(file_list)
full_path = os.path.join(directory, selected)
dict['mu_playlist'] = file_list
dict['mu_lib'] = file_list

# inputs
keyboard = bge.logic.keyboard
JUST_ACTIVATED = bge.logic.KX_INPUT_JUST_ACTIVATED

def initer(cont):
    own = cont.owner
    dict = bge.logic.globalDict
    if 'mplayback' not in dict:
        dict['mplayback'] = True
    if 'mp_inited' not in own:
        own['mp_inited'] = True
        print('Initializing music player')
        
        dict['mu_lib'] = file_list
        dict['mu_playlist'] = file_list
        dict['change_track'] = 0
        selected = random.choice(file_list)
        dict['mu_current_song'] = selected
        print('Current Track: ', dict['mu_current_song'])
        full_path = os.path.join(directory, selected)

        try:
            tag = TinyTag.get(full_path)
            print('Artist: %s' % tag.artist, 'Track: %s' % tag.title)
            dict['mu_artist'] = tag.artist
            dict['mu_title'] = tag.title            
        except:
            print("Track has no tag.")  
            
def stop_music(sound):

    print("Stop music")    
    sound.pauseSound()
    dict['mu_stopped'] = 1
    dict['music_player'] = 0
    
def play_music():

    print("Play music") 
    full_path = os.path.join(directory, dict['mu_current_song'])
    sound = bge.logic.getCurrentController().actuators['music_player']
    sound.sound = aud.Factory(full_path)
    sound.stopSound()
    sound.startSound()
    dict['mu_stopped'] = 0
    dict['change_track'] = 0
    dict['mu_track_time'] = 0 
    dict['music_player'] = 1  
    try:
        tag = TinyTag.get(full_path)
        print('Playing: ', 'Artist: %s' % tag.artist, 'Track: %s' % tag.title)
        dict['mu_artist'] = tag.artist
        dict['mu_title'] = tag.title
        info = ('Music > ', 'Artist: %s' % tag.artist, 'Track: %s' % tag.title)
        dict['music_info'] = info
    except:
        print("Track has no tag.") 
    print(dict['mu_title'], 'mu_title')
    
def next_track():

    print("next track")
    dict = bge.logic.globalDict
    plist = dict['mu_playlist']
    cur_song = dict['mu_current_song']
    pl_length = len(dict['mu_playlist'])    

    if pl_length > 1:
        try:
            plist.remove(cur_song)
        except:
            pass    

    if pl_length == 1:    
        print('rebuilding playlist')
        file_list = glob.glob(file_name)
        plist = file_list

    selected = random.choice(plist)
    dict['mu_last_track'] = dict['mu_current_song']
    dict['mu_current_song'] = selected
    dict['mu_playlist'] = plist
    dict['change_track'] = 0
    dict['mu_track_time'] = 0
    play_music()

def previous_track():

    print("previous track") 
    dict['mu_current_song'] = dict['mu_last_track']
    play_music()   

def check_status():

    sound = bge.logic.getCurrentController().actuators['music_player']
    cur_song = dict['mu_current_song']
    full_path = os.path.join(directory, dict['mu_current_song'])
    sound = bge.logic.getCurrentController().actuators['music_player']
    sound.sound = aud.Factory(full_path)  

    if sound.time < dict['mu_track_time'] and dict['mu_stopped'] == 0 and dict['change_track'] == 0:
        print('song over, getting new one')
        dict['change_track'] = 1
        dict['mu_track_time'] = 0
    else:
        dict['change_track'] = 0
    dict['mu_track_time'] = sound.time    

def main(cont):

    dict = bge.logic.globalDict        
    cur_song = dict['mu_current_song']    
    full_path = os.path.join(directory, dict['mu_current_song'])
    sound = bge.logic.getCurrentController().actuators['music_player']
    sound.sound = aud.Factory(full_path)
    sound.mode = 1
    initer(cont)
    if dict['music_player'] != 0:
        if dict['mu_stopped'] == 1:        
            play_music()
        if dict['change_track'] == 1:
            dict['change_track'] = 0
            next_track() 

    plist = dict['mu_playlist']  
    pl_length = len(dict['mu_playlist'])    
    if pl_length == 0:
        dict['mu_playlist'] = dict['mu_lib']       
         
    #allow controlls while paused or in replay    
    if dict['npause']  == 1 or dict['playback'] == True:
        if dict['yBut'] == False and dict['last_yBut'] == True:
            if dict['mu_stopped'] == 1:
                play_music() 
            else:
                stop_music(sound)  
        if dict['lBump'] == False and dict['last_lBump'] == True:
            previous_track()
        if dict['rBump'] == False and dict['last_rBump'] == True:
            next_track() 