/*
 * Copyright 2009 Funambol, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

#include "IConfigurationParser.h"
#include "serverexchange/firmware/DDProcessor.h"
#include <Logger/LoggerMacroses.h>

const char* const c_LogName = "DDProcessor";

using namespace NS_DM_Client;
using namespace NS_DM_Client::NS_Communication;

#define MIME_OCTET_STREAM   "application/octet-stream"

DDProcessor::DDProcessor() :
    size(0), m_isOctet(false), m_buffsize(2*1024), m_storedbytes(0), m_buffer(new char[m_buffsize])
{
    if(m_buffer == NULL) GDLWARN("new char");
    memset(m_buffer, '\0', m_buffsize);
}


DDProcessor::~DDProcessor()
{
    SAFE_DELETE_ARR(m_buffer);
}


int DDProcessor::AppendBuffer(void *buffer, int size)
{
    if (m_buffsize > m_storedbytes + size + 1)
    {
        memcpy(m_buffer + m_storedbytes, buffer, size);
        m_storedbytes += size;
        m_buffer[m_storedbytes] = '\0';
        return size;
    }
    return 0;
}


void DDProcessor::Parse()
{
    IConfigurationParser* parser = IConfigurationParser::GetInstance(IConfigurationParser::e_XML);

    parser->Init(m_buffer, "media");
    parser->GetProperty("objectURI", objectURI);
    parser->GetProperty("installNotifyURI", installNotifyURI);

    String propSize;
    parser->GetProperty("size", propSize);
    size = atoi(propSize.c_str());

    String mime;
    parser->GetProperty("type", mime);
    m_isOctet = strstr(mime.c_str(), MIME_OCTET_STREAM) != NULL;

    parser->Release();
}

