#!/usr/bin/python1.5
#
# mp3player.py: play MP3s - I think it is a nice example of what can be done with Buttons.
# Liscense: GPL
#
# Author: Defiant <mail@defiant.homedns.org>
#
# Settings:
# =========
# Set the MP3 Directory:

Custom_list = 0 # 1 for on - 0 means Auto Indexing the directory scripts/Custom/MP3/

MP3Dir = (0, 
        "scripts/Custom/MP3/unsorted",
        "scripts/Custom/MP3/Eminem/Eminem - The Eminem Show/",
        "scripts/Custom/MP3/Linkin Park/Meteora",
        "scripts/Custom/MP3/Guano Apes/Walking on a thin Line",
	"scripts/Custom/MP3/Beautiful/",
        "scripts/Custom/MP3/Ärzte/Unrockbar" # The last line doesn't have a ',' in the end!
        )
        
# example: MP3Dir = (0,
#	"scripts/Custom/MP3/unsorted",
#	"scripts/Custom/MP3/Linkin Park/",
#	"scripts/Custom/MP3/Linkin Park/Meteora/" # The last line doesn't have a ',' in the end!
#        )
#
# WARNING: Folders are CaSe-SeNsItIvE!
# All Settings done
# --

import App 
import MissionLib 
import Bridge.BridgeUtils 
import QuickBattle.QuickBattle
import string
import DynamicMusic
import Lib.LibEngineering
import nt

pBridge = App.g_kSetManager.GetSet('bridge') 
g_pScience = App.CharacterClass_GetObject(pBridge, "Science") 
pScienceMenu = Bridge.BridgeUtils.GetBridgeMenu("Science") 
pButtonPlayer = None
TrackNumber = 0
Tracklist = None
AllowPlayNext = 1
Shuffle = 0
restartCounter = 0
pButtonMP3Player = None
pButtonPlay = None
pButtonStop = None
pButtonNext = None
pButtonPrev = None
pButtonMasterVolume = None
pButtonModes = None
pButtonNP = None
pButtonDecrVolume = None
pButtonIncrVolume = None
pButtonQBMusic = None
pButtonShuffle = None
pButtonMP3Deactivate = None
pButtonMP3Activate = None
pButtonList = None
pButtonRedbook = None
playlist_index = 1
playlist_indexOld = 1
playlist_Buttons = {}
EventNumber = 0
mp3playeractive = 0
QBMusicActive = 0
use_Redbook = 0
RedbookCDLength = 0

MP3_MAIN = Lib.LibEngineering.GetEngineeringNextEventType()
MP3_TRACK_NEXT = Lib.LibEngineering.GetEngineeringNextEventType()
MP3_TRACK_PREV = Lib.LibEngineering.GetEngineeringNextEventType()
PLAY_ORDER = Lib.LibEngineering.GetEngineeringNextEventType()
ET_MP3_TIMER = Lib.LibEngineering.GetEngineeringNextEventType()
INCR_VOLUME = Lib.LibEngineering.GetEngineeringNextEventType()
DECR_VOLUME = Lib.LibEngineering.GetEngineeringNextEventType()
QB_MUSIC = Lib.LibEngineering.GetEngineeringNextEventType()
MP3_STOP = Lib.LibEngineering.GetEngineeringNextEventType()
MP3_ACTIVATE = Lib.LibEngineering.GetEngineeringNextEventType()
MP3_DEACTIVATE = Lib.LibEngineering.GetEngineeringNextEventType()
PLAY_REDBOOK = Lib.LibEngineering.GetEngineeringNextEventType()
TIMER_NEXT_REDBOOK = Lib.LibEngineering.GetEngineeringNextEventType()

MODINFO = { "Author": "\"Defiant\" mail@defiant.homedns.org",
            "Download": "http://defiant.homedns.org/~erik/STBC/MP3Player/",
            "Version": "1.1",
            "License": "GPL",
            "Description": "a (simple) MP3 and Audio-CD player for Bridge Commander :)"
            }


def getMP3Dir(dir = "scripts/Custom/MP3/"):
        global MP3Dir
        
        entry_done = 0
        
        try:
            Tracklist = nt.listdir(dir)
            Tracklist.sort()
        except:
            return
	
	for Entry in Tracklist:
		s = string.split(Entry, '.')
                extension = s[-1]
		if len(s) <= 1:
                    getMP3Dir(str(dir) + str(Entry) + str("/"))
                elif (string.lower(extension) == "mp3" or string.lower(extension) == "wav"):
                    if entry_done == 0:
                        MP3Dir.append(dir)
                        entry_done = 1


def MP3Play(pObject, pEvent):
        global MP3Dir, TrackNumber, Tracklist, Shuffle, pButtonNP, playlist_index, AllowPlayNext, mp3playeractive, pButtonMP3Activate, use_Redbook, playlist_indexOld, QBMusicActive

        QBMusicActive = 0
        
        if (AllowPlayNext == 0):
                return
        
        MP3files = {}
        Tracklist = None
        
        if (use_Redbook == 1):
            App.g_kRedbook.StopRedbookCDTrack()
            use_Redbook = 0

        # Unload the old Music
        DynamicMusic.UnloadMusic()

        if (pEvent.GetInt() == 0):
            if (use_Redbook == 1):
                if (App.g_kRedbook.PlayRedbookCDTrack(TrackNumber, 0, 0 ,0) == 0):
                    SetpButtonNP("None")
                    return
                TimerNextRedbookTrack()
                SetpButtonNP("CD Track: " + str(TrackNumber))
                # done for now
                return
        else:
            # of the Playlist Selector
            playlist_index = int(pEvent.GetInt())
                
        if (App.g_kRedbook.IsRedbookCDTrackFinishedPlaying() == 0):
            App.g_kRedbook.StopRedbookCDTrack()
        
        if (playlist_index != playlist_indexOld):
                TrackNumber = 0
        playlist_indexOld = playlist_index

        if (playlist_index == 0):
            playlist_index = 1
            TrackNumber = 0

        # Load the MP3 directory here:
        Tracklist = nt.listdir(MP3Dir[playlist_index])
        Tracklist.sort()
        
        i = 0
        for Song in Tracklist:
                MP3files[i] = Song
                i = i + 1
        
        for Filename in Tracklist:
                Song = getSongName(Filename)
                if (Song == 0):
                    continue
                LongFilename = MP3Dir[playlist_index] + "/" + Filename
                App.g_kMusicManager.LoadMusic(LongFilename, Song, 2.0)

        DisableTrackNextTimer()
        SongName = 0
        while (SongName == 0):
            if (Shuffle != 0):
                TrackNumber = App.g_kSystemWrapper.GetRandomNumber(len(Tracklist) - 1) + 1
            if (TrackNumber > len(Tracklist)): # catch playlist change
                TrackNumber = 0
            SongName = getSongName(Tracklist[TrackNumber])
            if (SongName == 0):
                TrackNumber = TrackNumber + 1
        
        SetpButtonNP(str(SongName))
        
        App.g_kMusicManager.StartMusic(SongName, 0)

	# This BroadcastHandler allows us to auto play the next track when the last one finished.
        pGame = App.Game_GetCurrentGame()
        App.g_kEventManager.AddBroadcastPythonFuncHandler(App.ET_MUSIC_DONE, pGame, __name__ + ".MP3TrackNext")


# Play next Track, either called by Button or by BroadcastHandler
def MP3TrackNext(pObject, pEvent):
    global TrackNumber, Tracklist, AllowPlayNext, pButtonNP, mp3playeractive, pButtonMP3Activate, use_Redbook, RedbookCDLength, QBMusicActive
    
    if (QBMusicActive == 1):
        return
    
    if (AllowPlayNext == 0):
        return
    
    if (use_Redbook == 1):
            if (Shuffle != 0):
                TrackNumber = App.g_kSystemWrapper.GetRandomNumber(RedbookCDLength - 1) + 1
            else:
                TrackNumber = TrackNumber + 1
                if (TrackNumber > RedbookCDLength):
                    TrackNumber = 1
                if (App.g_kRedbook.PlayRedbookCDTrack(TrackNumber, 0, 0 ,0) == 0):
                    SetpButtonNP("None")
                    return
                TimerNextRedbookTrack()
            
            SetpButtonNP("CD Track: " + str(TrackNumber))
            # we are done
            return
    if (App.g_kRedbook.IsRedbookCDTrackFinishedPlaying() == 0):
        App.g_kRedbook.StopRedbookCDTrack()
    
    DisableTrackNextTimer()
    
    SongName = 0
    while (SongName == 0): 
        if (Shuffle == 0):
                if (TrackNumber == len(Tracklist) - 1):
                        TrackNumber = 0
                else:
                        TrackNumber = TrackNumber + 1
        else:
                TrackNumber = App.g_kSystemWrapper.GetRandomNumber(len(Tracklist) - 1) + 1
    
        SongName = getSongName(Tracklist[TrackNumber])
    
    SetpButtonNP(str(SongName))
    App.g_kMusicManager.StartMusic(SongName, 0)


def MP3TrackPrev(pObject, pEvent):
    global TrackNumber, Tracklist, pButtonNP, mp3playeractive, pButtonMP3Activate, use_Redbook, RedbookCDLength

    if (use_Redbook == 1):
            if (Shuffle != 0):
                TrackNumber = App.g_kSystemWrapper.GetRandomNumber(RedbookCDLength - 1) + 1
            else:
                TrackNumber = TrackNumber - 1
                if (TrackNumber == 0):
                    TrackNumber = RedbookCDLength
                if (App.g_kRedbook.PlayRedbookCDTrack(TrackNumber, 0, 0 ,0) == 0):
                    SetpButtonNP("None")
                    return
                TimerNextRedbookTrack()
            
            SetpButtonNP("CD Track: " + str(TrackNumber))
            # we are done
            return
    if (App.g_kRedbook.IsRedbookCDTrackFinishedPlaying() == 0):
        App.g_kRedbook.StopRedbookCDTrack()

    DisableTrackNextTimer()
    
    SongName = 0
    while (SongName == 0):
        if (TrackNumber == 0):
                TrackNumber = len(Tracklist) - 1
        else:
                TrackNumber = TrackNumber - 1
        
        SongName = getSongName(Tracklist[TrackNumber])
    
    SetpButtonNP(str(SongName))
    App.g_kMusicManager.StartMusic(SongName, 0)


# Based off of Dasher's LoadExtraPlugins
def getSongName(Filename):
        if (string.find(str(Filename), ".") == "-1"):
            print("Unknown filetype for", Filename)
    
        s = string.split(Filename, '.')
        if len(s) <= 1:
            return 0
        # Indexing by -1 lets us be sure we're grabbing the extension. -Dasher42
        extension = s[-1]
        if (string.lower(extension) != "mp3" and string.lower(extension) != "wav"):
            print("Thats not a song we can play!")
            return 0
        Song = string.join(s[:-1], '.')
        return Song


# Problem: The Broadcast Handler is called every time when the Player just wants to play the next Track.
# We will just wait 4 seconds here before allowing that.
def DisableTrackNextTimer():
        global AllowPlayNext, ET_MP3_TIMER, pButtonNext, pButtonPrev, playlist_Buttons, mp3playeractive, pButtonMP3Activate
        
        # tests for Button bevor disabling them - to avoid the STUPID CRASH that appear!
        # I probably needed more time to fix this crash then writing the rest of this player!^
        if (mp3playeractive == 0):
            return
        if pButtonMP3Activate:
            return
        
        AllowPlayNext = 0

        pButtonNext.SetDisabled()
        pButtonPrev.SetDisabled()
        
        i = 1
        while (i <= len(playlist_Buttons)):
                playlist_Buttons[i].SetDisabled()
                i = i + 1
        
        # Create an event - it's a thing that will call this function
        pTimerEvent = App.TGEvent_Create()
        pTimerEvent.SetEventType(ET_MP3_TIMER)
        pTimerEvent.SetDestination(App.TopWindow_GetTopWindow())

	SDCounterTime = 4 #second(s)

	# Create a timer - it's a thing that will wait for a given time,then do something
	pTimer = App.TGTimer_Create()
	pTimer.SetTimerStart(App.g_kUtopiaModule.GetGameTime() + SDCounterTime)
	pTimer.SetDelay(0)
	pTimer.SetDuration(0)
	pTimer.SetEvent(pTimerEvent)
	App.g_kTimerManager.AddTimer(pTimer)


# ...and reanable here:
def reEnableTrackNext(pObject, pEvent):
    global AllowPlayNext, pButtonNext, pButtonPrev, playlist_Buttons, mp3playeractive, pButtonMP3Activate
    AllowPlayNext = 1
    
    # test again for their presence here
    if (mp3playeractive == 0):
            return
    if pButtonMP3Activate:
            return
            
    if pButtonNext and pButtonPrev:
        pButtonNext.SetEnabled()
        pButtonPrev.SetEnabled()
        
    i = 1
    while (i <= len(playlist_Buttons)):
        playlist_Buttons[i].SetEnabled()
        i = i + 1


# Function that looks if we play in normal or Random Order:
def SetShuffle(pObject, pEvent):
    global Shuffle, pButtonShuffle
    
    if (Shuffle == 0):
        pButtonShuffle.SetName(App.TGString("Shuffle:  On"))
        Shuffle = 1
    elif (Shuffle == 1):
        pButtonShuffle.SetName(App.TGString("Shuffle: Off"))
        Shuffle = 0
        

def IncrVolume(pObject, pEvent):
        global pButtonMasterVolume
        
        if (App.g_kMusicManager.GetVolume() <= 1):
                App.g_kMusicManager.SetVolume(App.g_kMusicManager.GetVolume() + 0.1)
        if (App.g_kMusicManager.GetVolume() > 0.9):
                App.g_kMusicManager.SetVolume(1)
        pButtonMasterVolume.SetName(App.TGString("Volume: " + str(int(App.g_kMusicManager.GetVolume()*10))))


def DecrVolume(pObject, pEvent):
        global pButtonMasterVolume
        
        if (App.g_kMusicManager.GetVolume() >= 0):
                App.g_kMusicManager.SetVolume(App.g_kMusicManager.GetVolume() - 0.1)
        if (App.g_kMusicManager.GetVolume() < 0.1):
                App.g_kMusicManager.SetVolume(0)
        pButtonMasterVolume.SetName(App.TGString("Volume: " + str(int(App.g_kMusicManager.GetVolume()*10))))


def MP3Stop(pObject, pEvent):
        global use_Redbook
        
        DisableTrackNextTimer()
        DynamicMusic.StopMusic()
        DynamicMusic.UnloadMusic()
        
        if (use_Redbook == 1):
            App.g_kRedbook.StopRedbookCDTrack()
            use_Redbook = 0
        else:
            if (App.g_kRedbook.IsRedbookCDTrackFinishedPlaying() == 0):
                App.g_kRedbook.StopRedbookCDTrack()

	# Remove BroadcastHandler
        pGame = App.Game_GetCurrentGame()
        App.g_kEventManager.RemoveBroadcastHandler(App.ET_MUSIC_DONE, pGame, __name__ + ".MP3TrackNext")


# When Player wants to here the normal BattleMusic again.
def QBMusic(pObject, pEvent):
        global pButtonNP, pButtonNext, pButtonPrev, MP3files, Tracklist, use_Redbook, QBMusicActive
        
        QBMusicActive = 1
        
        pButtonNP.SetName(App.TGString("np: None"))
        pButtonNext.SetDisabled()
        pButtonPrev.SetDisabled()
        MP3files = {}
        use_Redbook = 0
        
        pGame = App.Game_GetCurrentGame()
        
        MP3Stop(pObject, pEvent)
        
        if (App.g_kRedbook.IsRedbookCDTrackFinishedPlaying() == 0):
            App.g_kRedbook.StopRedbookCDTrack()
        
        import QuickBattle.QuickBattleGame
        
        QuickBattle.QuickBattleGame.SetupMusic(pGame)
        
        import LoadTacticalSounds
        LoadTacticalSounds.LoadSounds()


# Play Audio CD
def PlayRedbook(pObject, pEvent):
    global use_Redbook, RedbookCDLength, Shuffle, TrackNumber, QBMusicActive
    
    QBMusicActive = 0
    
    # 1. Stop
    MP3Stop(pObject, pEvent)
    # Another CD open?
    App.g_kRedbook.CloseRedbookCD()
    # 2. Open CD
    if (App.g_kRedbook.OpenRedbookCD() == 0):
        print("No Audio CD?")
        SetpButtonNP("None")
        return
    # else
    use_Redbook = 1
    
    # Get CD length - dirty! - TODO: If you know a better way, tell me!
    i = 1
    RedbookCDLength = 1
    while (RedbookCDLength != 0):
        RedbookCDLength = App.g_kRedbook.PlayRedbookCDTrack(i, 0, 0 ,0)
        i = i + 1
        
        # if we do too much tries:
        if (i > 50):
            print("Error on getting CD length")
            break; # leave the loop.
    # And stop after we found it
    App.g_kRedbook.StopRedbookCDTrack()
    
    RedbookCDLength = i - 2
    print("CD has", RedbookCDLength, "Tracks")
    # Play :))
    if (Shuffle != 0):
        TrackNumber = App.g_kSystemWrapper.GetRandomNumber(RedbookCDLength - 1) + 1
    else:
        TrackNumber = 1
    App.g_kRedbook.PlayRedbookCDTrack(TrackNumber, 0, 0 ,0) # I really don't know what the last 3 Values are for and 
    # the first one was just a guess...bad documentation :(
    
    # Finally set Button
    SetpButtonNP("CD Track: " + str(TrackNumber))
    # ...and set the timer
    TimerNextRedbookTrack()
    

# Play Next (auto)
def NextRedbookTrack(pObject, pEvent):
    global use_Redbook, RedbookCDLength, Shuffle, TrackNumber

    # ...just to make sure we still want audio...
    if (use_Redbook == 0):
        return
    
    # Finished old one?
    if (App.g_kRedbook.IsRedbookCDTrackFinishedPlaying() == 0):
        print("Track not finished")
        return

    if (Shuffle != 0):
        TrackNumber = App.g_kSystemWrapper.GetRandomNumber(RedbookCDLength - 1) + 1
    else:
        TrackNumber = TrackNumber + 1
    # Play next and also test if we successful playing the current one.
    if (App.g_kRedbook.PlayRedbookCDTrack(TrackNumber, 0, 0 ,0) == 1):
        TimerNextRedbookTrack()
    
    SetpButtonNP("CD Track: " + str(TrackNumber))


# yeah finally this is good :)
def SetpButtonNP(Text):
    global mp3playeractive, pButtonMP3Activate, pButtonNP
        # test again for their presence here
    if (mp3playeractive == 0):
        return
    if pButtonMP3Activate:
        return
    pButtonNP.SetName(App.TGString("NP: " + Text))


# Set the Timer
def TimerNextRedbookTrack():
    global use_Redbook, RedbookCDLength, Shuffle, TrackNumber, TIMER_NEXT_REDBOOK
    # Create an event - it's a thing that will call this function
    pTimerEvent = App.TGEvent_Create()
    pTimerEvent.SetEventType(TIMER_NEXT_REDBOOK)
    pTimerEvent.SetDestination(App.TopWindow_GetTopWindow())

    CounterTime = int(App.g_kRedbook.GetCDTrackLengthInMilliseconds(TrackNumber) / 1000)
    
    # Create a timer - it's a thing that will wait for a given time,then do something
    pTimer = App.TGTimer_Create()
    pTimer.SetTimerStart(App.g_kUtopiaModule.GetGameTime() + CounterTime)
    pTimer.SetDelay(0)
    pTimer.SetDuration(0)
    pTimer.SetEvent(pTimerEvent)
    App.g_kTimerManager.AddTimer(pTimer)


# Creates the 'MP3 System Activate' Button
def CreateFirstMP3Button():
        global pButtonMP3Activate, MP3_ACTIVATE, g_pScience, pScienceMenu

        g_pScience.AddPythonFuncHandlerForInstance(MP3_ACTIVATE, __name__ + ".CreateMP3Buttons") 
        pButtonMP3Activate = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Activate MP3 System"), MP3_ACTIVATE, 0, g_pScience) 
        pScienceMenu.PrependChild(pButtonMP3Activate)


# Create the BIG Button System here, when Activate calls:
def CreateMP3Buttons(pObject, pEvent):
        global g_pScience, pScienceMenu, mp3playeractive
        global MP3_MAIN, MP3_TRACK_NEXT, MP3_TRACK_PREV, PLAY_ORDER, ET_MP3_TIMER, INCR_VOLUME, DECR_VOLUME, QB_MUSIC, MP3_STOP, MP3_DEACTIVATE, MP3_ACTIVATE
        global pButtonMP3Player, pButtonPlay, pButtonStop, pButtonNext, pButtonPrev, pButtonMasterVolume, pButtonModes, pButtonNP, pButtonRedbook
        global pButtonDecrVolume, pButtonIncrVolume, pButtonQBMusic, pButtonShuffle, pButtonMP3Deactivate, pButtonMP3Activate, pButtonList

        pScienceMenu.DeleteChild(pButtonMP3Activate)
        pButtonMP3Activate = None
        
        g_pScience.AddPythonFuncHandlerForInstance(MP3_MAIN, __name__ + ".MP3Play") 
        pButtonPlay = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Play"), MP3_MAIN, 0, g_pScience) # Int has to be 1 here (playlist)

        g_pScience.AddPythonFuncHandlerForInstance(MP3_TRACK_NEXT, __name__ + ".MP3TrackNext") 
        pButtonNext = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Track +"), MP3_TRACK_NEXT, 0, g_pScience) 

        g_pScience.AddPythonFuncHandlerForInstance(MP3_TRACK_PREV, __name__ + ".MP3TrackPrev") 
        pButtonPrev = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Track -"), MP3_TRACK_PREV, 0, g_pScience)
        
        g_pScience.AddPythonFuncHandlerForInstance(PLAY_ORDER, __name__ + ".SetShuffle") 
        pButtonShuffle = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Shuffle: Off"), PLAY_ORDER, 0, g_pScience) 

        g_pScience.AddPythonFuncHandlerForInstance(INCR_VOLUME, __name__ + ".IncrVolume") 
        pButtonIncrVolume = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Increment"), INCR_VOLUME, 0, g_pScience) 

        g_pScience.AddPythonFuncHandlerForInstance(DECR_VOLUME, __name__ + ".DecrVolume") 
        pButtonDecrVolume = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Decrement"), DECR_VOLUME, 0, g_pScience) 

        g_pScience.AddPythonFuncHandlerForInstance(QB_MUSIC, __name__ + ".QBMusic") 
        pButtonQBMusic = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Play QB-Music"), QB_MUSIC, 0, g_pScience) 

        g_pScience.AddPythonFuncHandlerForInstance(MP3_STOP, __name__ + ".MP3Stop") 
        pButtonStop = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Stop"), MP3_STOP, 0, g_pScience)
        
        g_pScience.AddPythonFuncHandlerForInstance(MP3_DEACTIVATE, __name__ + ".DeleteMP3Buttons") 
        pButtonMP3Deactivate = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Deactvate MP3 System"), MP3_DEACTIVATE, 0, g_pScience) 

        g_pScience.AddPythonFuncHandlerForInstance(PLAY_REDBOOK, __name__ + ".PlayRedbook") 
        pButtonRedbook = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Play Audio CD"), PLAY_REDBOOK, 0, g_pScience)
        
        pButtonMP3Player = App.STMenu_CreateW(App.TGString("MP3 Player"))
        pButtonMasterVolume = App.STMenu_CreateW(App.TGString("Volume: " + str(int(App.g_kMusicManager.GetVolume()*10))))
        pButtonModes = App.STMenu_CreateW(App.TGString("Modes"))
        pButtonNP = App.STMenu_CreateW(App.TGString("NP: None"))
        pButtonList = App.STMenu_CreateW(App.TGString("Playlist"))
        
        pScienceMenu.PrependChild(pButtonMP3Player)
        
        pButtonMP3Player.PrependChild(pButtonPlay)
        pButtonMP3Player.PrependChild(pButtonStop)
        pButtonMP3Player.PrependChild(pButtonNext)
        pButtonMP3Player.PrependChild(pButtonPrev)
        pButtonMP3Player.PrependChild(pButtonMasterVolume)
        pButtonMP3Player.PrependChild(pButtonModes)
        pButtonMP3Player.PrependChild(pButtonNP)

        pButtonMasterVolume.PrependChild(pButtonDecrVolume)
        pButtonMasterVolume.PrependChild(pButtonIncrVolume)
        
        pButtonModes.PrependChild(pButtonQBMusic)
        pButtonModes.PrependChild(pButtonShuffle)
        pButtonModes.PrependChild(pButtonMP3Deactivate)
        pButtonModes.PrependChild(pButtonList)
        pButtonModes.PrependChild(pButtonRedbook)

        pButtonNP.SetDisabled()
        
        CreatePlaylistButtons()
        
        mp3playeractive = 1


# Delete Buttons - when Player clicks on MP3Deactivate
def DeleteMP3Buttons(pObject, pEvent):
        global g_pScience, pScienceMenu, Shuffle, mp3playeractive
        global MP3_MAIN, MP3_TRACK_NEXT, MP3_TRACK_PREV, PLAY_ORDER, ET_MP3_TIMER, INCR_VOLUME, DECR_VOLUME, QB_MUSIC, MP3_STOP, MP3_DEACTIVATE, MP3_ACTIVATE
        global pButtonMP3Player, pButtonPlay, pButtonStop, pButtonNext, pButtonPrev, pButtonMasterVolume, pButtonModes, pButtonNP, pButtonList, pButtonRedbook
        global pButtonDecrVolume, pButtonIncrVolume, pButtonQBMusic, pButtonShuffle, pButtonMP3Deactivate, pButtonMP3Activate, playlist_Buttons
        
        Shuffle = 0
        mp3playeractive = 0
        
        i = 1
        while (i <= len(playlist_Buttons)):
                pButtonList.DeleteChild(playlist_Buttons[i])
                i = i + 1
        
        pButtonModes.DeleteChild(pButtonRedbook)
        pButtonModes.DeleteChild(pButtonList)
        pButtonModes.DeleteChild(pButtonQBMusic)
        pButtonModes.DeleteChild(pButtonShuffle)
        pButtonModes.DeleteChild(pButtonMP3Deactivate)
        
        pButtonMasterVolume.DeleteChild(pButtonDecrVolume)
        pButtonMasterVolume.DeleteChild(pButtonIncrVolume)
        
        pButtonMP3Player.DeleteChild(pButtonPlay)
        pButtonMP3Player.DeleteChild(pButtonStop)
        pButtonMP3Player.DeleteChild(pButtonNext)
        pButtonMP3Player.DeleteChild(pButtonPrev)
        pButtonMP3Player.DeleteChild(pButtonMasterVolume)
        pButtonMP3Player.DeleteChild(pButtonModes)
        pButtonMP3Player.DeleteChild(pButtonNP)
        
        pScienceMenu.DeleteChild(pButtonMP3Player)

        CreateFirstMP3Button()


def CreatePlaylistButtons():
    global playlist_index, MP3Dir, pButtonList, g_pScience, EventNumber, playlist_Buttons, Custom_list

    if Custom_list == 0:
        MP3Dir = [0] # recreate the list with dummy
        getMP3Dir()

    i = 1
    # Create a Button for every Directory
    while (i < len(MP3Dir)):
        # 1. Create a new Event-number
        EventNumber = Lib.LibEngineering.GetEngineeringNextEventType()
        # 3. Setup Event Handler
        g_pScience.AddPythonFuncHandlerForInstance(EventNumber, __name__ + ".MP3Play") 
        # 4. Get the last folder name:
        Folders = string.split(MP3Dir[i], '/')
        FolderName = Folders[-1]
        if (FolderName == ""):
            FolderName = Folders[-2]
        # 5. create the Button
        playlist_Buttons[i] = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString(FolderName), EventNumber, i, g_pScience) 
        # 6. And finally add the Button:
        pButtonList.PrependChild(playlist_Buttons[i])
        # i++
        i = i + 1

    
# Thats for fixing against the ftb: sleight42 has Programmed the Carrier System to kill the whole Menu on every click.
def Restart():
        # obsolete now with the new ftb Version
        return
        global restartCounter
        if (restartCounter == 2): # every ftb click will call restart() 2 times, so we count
                CreateFirstMP3Button()
                restartCounter = 1 # first count on Start is from 0, then from 1
        else:
            restartCounter = restartCounter + 1
            # recreate it:
            if (mp3playeractive == 1):
                CreateMP3Buttons(None, None)


def init():
    # Create Button the first time:
    CreateFirstMP3Button()
    App.TopWindow_GetTopWindow().AddPythonFuncHandlerForInstance(ET_MP3_TIMER, __name__ + ".reEnableTrackNext")
    App.TopWindow_GetTopWindow().AddPythonFuncHandlerForInstance(TIMER_NEXT_REDBOOK, __name__ + ".NextRedbookTrack")
