/*
 * 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 "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;
}


