# 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.
#
# Topic: FBFolderPopup, FBTake, FBApplication.FileOpen
#
from pyfbsdk import FBApplication, FBSystem, FBFolderPopup
from nt import listdir

# Create global objects needed for our work...
lApplication = FBApplication()
lSystem = FBSystem()

# Let the user select the folder where the FBX files are...
lFolderPopup = FBFolderPopup()
lFolderPopup.Caption = "Select the folder where all the FBX files are located"

if lFolderPopup.Execute():
    lFileList = listdir( lFolderPopup.Path )

    for lFile in lFileList:
        if lFile.endswith( '.fbx' ):

            lFileFullPath = "%s\\%s" % ( lFolderPopup.Path, lFile )

            # Open the FBX file
            print"Message: Opening file '%s'" % lFileFullPath
            lApplication.FileOpen( lFileFullPath )

            # First obtain the name of the current FBX file, and
            # remove the trailing '.fbx' extention.
            lName = lFile.replace( ".fbx", "" )

            # The use that name for the first take in the list of takes...
            # If the takes have not been re-ordered and renamed, it will be
            # the take named 'Take 001' that will be renamed.
            print "Message: Renaming take '%s' to '%s'" % ( lSystem.Scene.Takes[0].Name, lName )
            lSystem.Scene.Takes[0].Name = lName

            # Save the new file.
            # Warning: media will not be embedded!
            print "Message: Saving file '%s'\n" % lFileFullPath
            lApplication.FileSave( lFileFullPath )

            # Clear the scene.
            lApplication.FileNew()

            # Cleanup local variables
            del( lName, lFileFullPath )

    # Cleanup local variables
    del( lFileList, lFile )

# Cleanup

# Cleanup things from pyfbsdk
del( FBApplication, FBSystem, FBFolderPopup )

# Cleanup things from nt
del( listdir )

# Cleanup local variables
del( lApplication, lSystem, lFolderPopup )