# 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: FBTake, FBFbxManager, FBFileDlg, 
#

from pyfbsdk import FBSystem, FBApplication, FBFbxManager, FBFilePopup, FBFilePopupStyle

# First get some needed objects.
lSystem      = FBSystem()
lApplication = FBApplication()
lFileName    = lApplication.FBXFileName
if lFileName == "":## If no FBX file has been loaded.
    FileDlg = FBFilePopup()
    FileDlg.Style = FBFilePopupStyle.kFBFilePopupSave
    FileDlg.Caption = "The current filename is not valid."
    FileDlg.FileName = "Untitled.fbx"
    if FileDlg.Execute():
        lFileName = FileDlg.FileName

# We want to make sure that we have a scene with file name
# already, otherwise we might want to open a file popup.
# For now we assume that there is already a name to use as a
# base name.
if lFileName.upper().endswith( '.FBX' ):

    lMgr = FBFbxManager()

    # Since we will need to change the current take as we
    # save them, we keep the orginal take around to reset
    # it afterwards.
    lOriginalTake = lSystem.CurrentTake

    # Iterate the list of takes.
    for lTake in lSystem.Scene.Takes:

        # Switch the current take to the one we want to save.
        lSystem.CurrentTake = lTake

        # Build the file name to use. Here we use the same pattern
        # MotionBuilder would use.
        lTakeFileName = "%s-%s.fbx" % ( lFileName[:-4], lTake.Name )

        # Some feedback for the user...
        print "Saving Take '%s' to file '%s'" % ( lTake.Name, lTakeFileName )

        # Go through the actual process of saving to the file.
        # WARNING: We do not do any error checking on the return
        #          values of SaveBegin()/Save()/SaveEnd()!!!
        lMgr.SaveBegin( lTakeFileName )

        # Let's save to ASCII format.
        lMgr.UseASCIIFormat = True

        # Go through the list of takes to export to tag only
        # the correct take. All the other are disregarded.
        for lTakeSave in lMgr.Takes:
            if lTakeSave.Name != lTake.Name:
                lTakeSave.Import = False

            # Cleanup
            del( lTakeSave )

        lMgr.Save()
        lMgr.SaveEnd()

        # Cleanup.
        del( lTake, lTakeFileName )

    # Return the current take to the original.
    lSystem.CurrentTake = lOriginalTake

    del( lMgr, lOriginalTake )

else:

    print 'File name does not end with ".fbx". Unable to proceed!'


# Cleanup of local variables.
del( lSystem, lApplication, lFileName )

# Cleanup of imported symbols.
del( FBSystem, FBApplication, FBFbxManager )