/*
 * Copyright (C) 2009 - 2010 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

/* $Id$ */

#include "NotificationListener/WSPPushDecoder.h"

using namespace NS_DM_Client;
using namespace NS_DM_Client::NS_NotificationListener;
using namespace NS_DM_Client::NS_WSP;

WSPPushDecoder::WSPPushDecoder()
{
}

bool    WSPPushDecoder::SetPDU(const void* PDU, size_t size, bool connectionless)
{
    const int PDUTypeOffset = (connectionless) ? 1 : 0;
    const char* ptr = static_cast<const char*>(PDU);
    if (ptr[PDUTypeOffset] != e_Push)
    {
        return false;
    }

    m_pdu.resize(size);
    if (m_pdu.size() != size)
    {
        return false;
    }

    memcpy(&m_pdu[0], PDU, size);

    m_connectionless = connectionless;
    return true;
}


bool    WSPPushDecoder::GetDataInfo(int& offsetFromPDUStart, int& size) const
{
    const int PDUTypeOffset = (m_connectionless) ? 1 : 0;
    const int PDUTypeSize = 1;

    buffer_t::const_pointer ptr = &m_pdu[0];

    // get Header Length field value and size
    ptr += PDUTypeOffset + PDUTypeSize;
    int hdrLenSize = 0;
    unsigned hdrLen = S_parseUintVar(ptr, &hdrLenSize);

    offsetFromPDUStart = ptr + hdrLen + hdrLenSize - &m_pdu[0];
    size = m_pdu.size() - offsetFromPDUStart;
    return size != 0;
}


const char*    WSPPushDecoder::getContentTypeRef() const
{
	const int PDUTypeOffset = (m_connectionless) ? 1 : 0;
	const int PDUTypeSize = 1;

	const char* ptr = reinterpret_cast<const char*>(&m_pdu[0]);

	// get Header Length field value and size
	ptr += PDUTypeOffset + PDUTypeSize;
	int hdrLenSize = 0;
	//    unsigned hdrLen =
	S_parseUintVar(ptr, &hdrLenSize);

	// get Content type
	ptr += hdrLenSize;
	char c = *ptr;
	if (!S_get7bitValue(c))
	{
		const char* data = NULL;
		//        int lenContType =
		S_parseMultipleOctetsLengthVar(ptr, data);

		ptr = data;
	}

	return ptr;
}


const char*    WSPPushDecoder::GetNotWNContentTypeRef() const
{
	return getContentTypeRef();
}


NS_WSP::EnumContentTypes    WSPPushDecoder::GetWNContentType_MIMEType() const
{
//     const int PDUTypeOffset = (m_connectionless) ? 1 : 0;
//     const int PDUTypeSize = 1;
// 
//     const char* ptr = reinterpret_cast<const char*>(&m_pdu[0]);
// 
//     // get Header Length field value and size
//     ptr += PDUTypeOffset + PDUTypeSize;
//     int hdrLenSize = 0;
// //    unsigned hdrLen =
// 		S_parseUintVar(ptr, &hdrLenSize);
// 
//     // get Content type
//     ptr += hdrLenSize;
//     char c = *ptr;
//     if (!S_get7bitValue(c))
//     {
//         const char* data = NULL;
// //        int lenContType =
// 			S_parseMultipleOctetsLengthVar(ptr, data);
//        c = *data;
		char c = *getContentTypeRef();
        if (!S_get7bitValue(c))
        {
            return e_CT_NotWellKnown;
        }
//    }

    NS_WSP::EnumContentTypes contentType = static_cast<NS_WSP::EnumContentTypes>(c);
    return contentType;
}


unsigned int     WSPPushDecoder::S_parseUintVar(const char* buf, int* varLen)
{
    const unsigned CONTINUE_LONG_FIELD_MASK = 0x80;
    const unsigned LONG_FIELD_DATA_MASK = 0x7F;
    const unsigned LONG_FIELD_DATA_BIT_LEN = 7;

    unsigned int n = 0;
    const char* ptr = buf;
    for (bool end = false; !end; ++ptr)
    {
        end = (*ptr & CONTINUE_LONG_FIELD_MASK) == 0;
        n <<= LONG_FIELD_DATA_BIT_LEN;
        n |= *ptr & LONG_FIELD_DATA_MASK;
    }

    if (varLen)
    {
        *varLen = ptr - buf;
    }

    return n;
}


bool         WSPPushDecoder::S_get7bitValue(char& val)
{
    const unsigned char _7BIT_VALUE_MASK = 0x80;

    if (val & _7BIT_VALUE_MASK)
    {
        val ^= _7BIT_VALUE_MASK;
        return true;
    }

    return false;
}


/*
Value Interpretation of First Octet
0-30    This octet is followed by the indicated number (0 - 30) of data octets
31      This octet is followed by a uintvar, which indicates the number of data octets after it
32-127  The value is a text string, terminated by a zero octet (NUL character)
28-255  It is an encoded 7-bit value; this header has no more data
*/
int     WSPPushDecoder::S_parseMultipleOctetsLengthVar(const char* buf_ptr, const char*& skipLenVarPtr)
{
    const char LENGTH_QUOTE = '\x1F';
    const char _7BIT_VALUE_MASK = '\x80';

    int lenValue = 0;
    if (*buf_ptr & _7BIT_VALUE_MASK)
    {
        lenValue = 0;
        skipLenVarPtr = NULL;
    }
    else if (*buf_ptr <= 30)
    {
        lenValue = *buf_ptr;
        skipLenVarPtr = buf_ptr + 1;
    }
    else if (*buf_ptr == LENGTH_QUOTE)
    {
        int lenVarSize = 0;
        lenValue = S_parseUintVar(&buf_ptr[1], &lenVarSize);
        skipLenVarPtr = &buf_ptr[1] + lenVarSize;
    }
    else // 32 -127
    {
        skipLenVarPtr = buf_ptr;
        if (*buf_ptr == '\"')
        {
            ++skipLenVarPtr;
        }

        lenValue = strlen(skipLenVarPtr);
    }

    return lenValue;
}


