#include "fbxsdkutility.h"

#ifdef  IOS_REF
#undef  IOS_REF
#define IOS_REF (*(pSdkManager->GetIOSettings()))
#endif


FbxManager* gSdkManager = NULL;
FbxScene* gScene = NULL;

namespace Fbx
{

void InitializeSdkManagerAndScene()
{
    // Create the FBX SDK memory manager object.
    // The SDK Manager allocates and frees memory
    // for almost all the classes in the SDK.
    gSdkManager = FbxManager::Create();

    // create an IOSettings object
    FbxIOSettings* ios = FbxIOSettings::Create(gSdkManager, IOSROOT);
    gSdkManager->SetIOSettings(ios);

    gScene = FbxScene::Create(gSdkManager, "");
}

void DestroySdkObjects(FbxManager* pSdkManager, bool pExitStatus)
{
    // Delete the FBX SDK manager. All the objects that have been allocated
    // using the FBX SDK manager and that haven't been explicitly destroyed
    // are automatically destroyed at the same time.
    if (pSdkManager)
        pSdkManager->Destroy();
    if (pExitStatus)
        FBXSDK_printf("SdkManager destroy Success!\n");
}

const FbxNode* GetRootNode()
{
    return gScene->GetRootNode();
}

const char* GetRootNodeName()
{
    return GetRootNode()->GetName();
}


bool SaveFbx(const char *filename)
{
    // Create an exporter.
    FbxExporter* lExporter = FbxExporter::Create(gSdkManager, "");

    // 0 FBX binary(*.fbx)
    // 1 FBX ascii(*.fbx)
    // 2 FBX encrypted(*.fbx)
    // 3 FBX 6.0 binary(*.fbx)
    // 4 FBX 6.0 ascii(*.fbx)
    // 5 FBX 6.0 encrypted(*.fbx)
    // 6 AutoCAD DXF(*.dxf)
    // 7 Alias OBJ(*obj)
    // 8 Collada DAE(*dae)
    // 9 Biovision BVH(*.bvh)
    // 10 Motion Analysis HTR(*.htr)
    // 11 Motion Analysis TRC(*.trc)
    // 12 Acclaim ASF(*asf)
    // 13 Acclaim AMC(*amc)
    // 14 Vicon C3D(*.C3D)
    // 15 Adaptive Optics AOA(*.aoa)
    // 16 Superfluo MCD(*.mcd)

    // 真JB蛋疼，如果将输出格式索引，设置为3，那么纹理总是绑定不上
    // 尝试了不下于500次测试，一万个草泥马在脑中奔腾
    int outFileFormat = 0;
    bool lExportStatus = lExporter->Initialize(filename, outFileFormat, gSdkManager->GetIOSettings());

    if (!lExportStatus)
    {
        printf("Call to FbxExporter::Initialize() failed.\n");
        printf("Error returned: %s\n\n", lExporter->GetStatus().GetErrorString());
        return false;
    }

    // Export the scene to the file.
    lExporter->Export(gScene);

    // Destroy the exporter.
    lExporter->Destroy();

    // Destroy the reference scene.
    gScene->Destroy();
    gScene = NULL;

    return true;
}

}
