/** \file
 *
 *  Contains the XmlAPI class implementation.
 *
 *  Copyright (c) 2007,2008,2009 MBARI
 *  MBARI Proprietary Information.  All Rights Reserved
 *
 */

#include "XmlAPI.h"

#include "xml/XmlNode.h"
#include "../../Lib/tinyxml/tinyxml.h"

XmlAPI XmlAPI::Instance_;

XmlAPI::~XmlAPI()
{
}

/// Load the mission with the indicated filename
/// In case of error, log message with indicated severity
MissionNode* XmlAPI::loadMissionFile( const char* filename, Logger& logger,
                                      Syslog::Severity severity )
{
    return LoadMissionFile( filename, logger, severity );
}

/// Static function to load the mission with the indicated filename
/// In case of error, log message with indicated severity
MissionNode* XmlAPI::LoadMissionFile( const char* filename, Logger& logger,
                                      Syslog::Severity severity )
{
    Str xmlFilename( filename );
    size_t extIndex = xmlFilename.findLastOf( ".tl" );
    if( extIndex != Str::NO_POS )
    {
        xmlFilename = xmlFilename.substr( 0, extIndex ) + ".tx";
        // for now, use Syslog::IMPORTANT to facilitate inspection (later on, DEBUG is probably better)
        logger.syslog( Str( "Loading Compiled TethysL script from file " ) + xmlFilename, Syslog::IMPORTANT );
    }
    TiXmlDocument* xmlDoc = new TiXmlDocument( xmlFilename.cStr() );

    if( !xmlDoc->LoadFile() )
    {
        logger.syslog( Str( "Cannot load Xml file " ) + xmlFilename + " due to: " + xmlDoc->ErrorDesc(), severity );
        delete xmlDoc;
        return NULL;
    }

    XmlNode* xmlNode = new XmlNode( xmlDoc );

    //xmlNode->debugPrint();

    return xmlNode;
}

/// Static function to parse the mission from the provided xml string
MissionNode* XmlAPI::ParseMission( const char* xmlString, Logger& logger,
                                   Syslog::Severity severity )
{
    TiXmlDocument* xmlDoc = new TiXmlDocument();

    xmlDoc->Parse( xmlString );
    if( xmlDoc->Error() )
    {
        logger.syslog( Str( "Cannot parse xml: " ) + xmlString + " due to: " + xmlDoc->ErrorDesc(), severity );
        delete xmlDoc;
        return NULL;
    }

    XmlNode* xmlNode = new XmlNode( xmlDoc );

    //xmlNode->debugPrint();

    return xmlNode;
}

XmlAPI::XmlAPI()
    : MissionAPI( "Xml", ".xml" )
{
    // Also allow for .tx extension
    MissionAPIRegistry::Register( "Tx", ".tx", this );
    // Also allow TethysL source file extension, which is simply handled as .tx
    // (direct TethysL source parsing is not supported at the moment)
    MissionAPIRegistry::Register( "TethysL", ".tl", this );
}

