#include <wbxml.h>
#include <wbxml_mem.h>

#include <spds/SyncMLProcessor.h>
#include "WBXMLUtils.h"

using namespace NS_DM_Client::NS_Common;

#define DEFAULT_ERROR 4444

int WBXMLUtils::Parse(const char *wbxml, const unsigned int wbxmllength, Funambol::SyncML **syncml)
{
    if (!wbxml || !wbxmllength || !syncml) return DEFAULT_ERROR;

    WBXMLError ret = WBXML_OK;
    WB_UTINY *xml = NULL;
    WB_ULONG  xml_len = 0;

    WB_UTINY *utinywbxml = (WB_UTINY *) const_cast<char *>(wbxml);

    ret = wbxml_conv_wbxml2xml_withlen(utinywbxml, wbxmllength, &xml, &xml_len, NULL);
    if (ret != WBXML_OK)
    {
        return ret;
    }

    if (xml)
    {
        Funambol::SyncMLProcessor processor;
        *syncml = processor.processMsg((char *)xml);
        wbxml_free(xml);
        return WBXML_OK;
    }
    else
    {
        return DEFAULT_ERROR; // smth not 0 and > than WBXMLError largest value
    }
}


int WBXMLUtils::Parse(const char *wbxml, const unsigned int wbxmllength, char **xml)
{
    if (!wbxml || !wbxmllength) return DEFAULT_ERROR;

    WB_ULONG  xml_len = 0;
    WB_UTINY *utinywbxml = (WB_UTINY *) const_cast<char *>(wbxml);

    return wbxml_conv_wbxml2xml_withlen(utinywbxml, wbxmllength, (WB_UTINY **) xml, &xml_len, NULL);
}


int WBXMLUtils::FormatToWBXML(const char *syncml, const char **wbxml, unsigned int *wbxmllength)
{
    WB_UTINY *utinyxml = (WB_UTINY *) const_cast<char *>(syncml);
    WB_UTINY **utinywbxml = (WB_UTINY **) const_cast<char **>(wbxml);
    return wbxml_conv_xml2wbxml_withlen(utinyxml, strlen(syncml), utinywbxml, wbxmllength, NULL);
}

