# Copyright 2009 Autodesk, Inc.  All rights reserved.
# Use of this software is subject to the terms of the Autodesk license agreement 
# provided at the time of installation or download, or which otherwise accompanies
# this software in either electronic or hard copy form.
#
# Script description:
#  MotionBuilder 2009 and Pre-Visualization Demo 2
#
# Topic: FBAudioClip, FBStoryClip, FBStoryTrack, FBStoryTrackType, FBFilePopup
# 

from pyfbsdk import *
from pyfbsdk_additions import *
from sys import *
import os.path
import traceback

global lFp
lFp = FBFilePopup()

#There would need to be more error handling added if an unperfect audio track definition files were added.
#There would be to be some error handling if you are trying to put an audio file that is bigger then the assigned frames for it
def BrowseCallback(control, event):
    #OPENING AND FILE READING
    #Create the popup and set necessary initial values.
    lFp.Caption = "Select the audio track definition file:"
    lFp.Style = FBFilePopupStyle.kFBFilePopupOpen
    lFp.Filter = "*.txt"     # BUG: If we do not set the filter, we will have an exception.
    if os.path.isdir(os.path.splitext(traceback.extract_stack()[-1][0])[0]):
        lFp.Path = os.path.normpath(os.path.splitext(traceback.extract_stack()[-1][0])[0])
    else:
        lFp.Path = os.path.normpath(os.path.dirname(traceback.extract_stack()[-1][0]))
    lRes = lFp.Execute() # Get the GUI to show.

    if lRes: #Check to see if a file was set, if so set the edit box to the file path and name
        eButt.Text = os.path.join(lFp.Path,lFp.FileName) #set up the edit box to contain the path

def SetupCallback(control, event):
    #Check to see if a valid file was selected.
    try:
        f=open(os.path.join(lFp.Path,lFp.FileName), 'r') #Open the Audio Track Definition File
        shotInfoFile = f.readlines() #Read all the content of Audio Track Definition File
        f.close() #Close the file that you were reading
        lTrackAudio = FBStoryTrack(FBStoryTrackType.kFBStoryTrackAudio) #add a new Audio track to the Story tool
        shotCnt = len(shotInfoFile) #Find out how many lines were in the file
        counter = 1
        lastClipEnd = 0
        for shotInfo in shotInfoFile:
            #PARSING THE STRINGS
            shots = shotInfo.split() # Spitting the lines in the file
            shotName = shots[0]
            shotStart = shots[1]
            shotEnd = shots[2]
            iShotStart = int(shotStart)
            iShotEnd = int(shotEnd)
            if counter < 10:
                audioPath = os.path.join(lFp.Path,"Audio_Clip_0" + str(counter) + ".wav")
            else:
                audioPath = os.path.join(lFp.Path,"Audio_Clip_" + str(counter) + ".wav")

            lAudio = FBAudioClip(audioPath)
            lClip = FBStoryClip (lAudio, lTrackAudio, FBTime(0,0,0,iShotStart))
            if lastClipEnd<iShotEnd: lastClipEnd=iShotEnd
            counter = counter + 1
        FBPlayerControl().LoopStop=FBTime(0,0,0,lastClipEnd,0)## Set the end of the player control at the end of the last clip

    except IOError:
        FBMessageBox( "Cannot Continue", "Unable to read the audio track definition file you selected or you have not selected one.", "OK", None, None )
        exit

def CloseCallback(control, event):
    DestroyTool(t)

def PopulateLayout(mainLyt):

    #1.  Creating the instruction title
    l = FBLabel()
    l.Caption = "Select the audio track definition file to use:"
    l.Style = FBTextStyle.kFBTextStyleBold
    l.WordWrap = True

    x = FBAddRegionParam(0,FBAttachType.kFBAttachLeft,"") # Create a label that is left justify 
    y = FBAddRegionParam(5,FBAttachType.kFBAttachTop,"") # ... and at the top of the layout. 
    w = FBAddRegionParam(300,FBAttachType.kFBAttachNone,"") # its width is fixed at 300 pixels
    h = FBAddRegionParam(20,FBAttachType.kFBAttachNone,"") # and its height is fixed at 15 pixels

    mainLyt.AddRegion("lab","lab", x, y, w, h)
    mainLyt.SetControl("lab",l)

    #2.  Creating a temp button for a place holder
    e = FBEdit()
    e.ReadOnly = True
    e.Text = ""

    x2 = FBAddRegionParam(5,FBAttachType.kFBAttachLeft,"")
    y2 = FBAddRegionParam(5,FBAttachType.kFBAttachBottom,"lab")
    w2 = FBAddRegionParam(220,FBAttachType.kFBAttachNone,"")
    h2 = FBAddRegionParam(20,FBAttachType.kFBAttachNone,"")

    mainLyt.AddRegion("path","path", x2, y2, w2, h2)
    mainLyt.SetControl("path",e)

    #3.  Creating a the browse button
    b2 = FBButton()
    b2.Caption = "Browse..."
    b2.Justify = FBTextJustify.kFBTextJustifyCenter

    x3 = FBAddRegionParam(225,FBAttachType.kFBAttachLeft,"path")
    y3 = FBAddRegionParam(5,FBAttachType.kFBAttachBottom,"lab")
    w3 = FBAddRegionParam(57,FBAttachType.kFBAttachNone,"")
    h3 = FBAddRegionParam(20,FBAttachType.kFBAttachNone,"")

    mainLyt.AddRegion("but","but", x3, y3, w3, h3)
    mainLyt.SetControl("but",b2)

    global eButt #setting the FBEdit button global so it can be set from the function BrowseCallback
    eButt = e
    b2.OnClick.Add(BrowseCallback)

    #4. Creating the button the automatically does everything
    b3 = FBButton()
    b3.Caption = "Setup Audio"
    b3.Justify = FBTextJustify.kFBTextJustifyCenter

    x4 = FBAddRegionParam(40,FBAttachType.kFBAttachLeft,"")
    y4 = FBAddRegionParam(12,FBAttachType.kFBAttachBottom,"path")
    w4 = FBAddRegionParam(100,FBAttachType.kFBAttachNone,"")
    h4 = FBAddRegionParam(25,FBAttachType.kFBAttachNone,"")

    mainLyt.AddRegion("audio","audio", x4, y4, w4, h4)
    mainLyt.SetControl("audio",b3)
    b3.OnClick.Add(SetupCallback)

    #5.  Creating a close
    b4 = FBButton()
    b4.Caption = "Close"
    b4.Justify = FBTextJustify.kFBTextJustifyCenter

    x5 = FBAddRegionParam(20,FBAttachType.kFBAttachRight,"audio")
    y5 = FBAddRegionParam(12,FBAttachType.kFBAttachBottom,"path")
    w5 = FBAddRegionParam(100,FBAttachType.kFBAttachNone,"")
    h5 = FBAddRegionParam(25,FBAttachType.kFBAttachNone,"")

    mainLyt.AddRegion("close","close", x5, y5, w5, h5)
    mainLyt.SetControl("close",b4)
    b4.OnClick.Add(CloseCallback)

def CreateTool():
    # Tool creation will serve as the hub for all other controls
    global t
    t = CreateUniqueTool("Audio Track Setup Tool")
    t.StartSizeX = 300
    t.StartSizeY = 123
    PopulateLayout(t)
    ShowTool(t)

CreateTool()