/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: atotime.cpp,v 1.1.2.1 2004/07/09 01:50:20 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

/////////////////////////////////////////////////////////////////////////////
//
//  ATOTIME.CPP
//
//
//  This file contains the functions that are used in RealText rendering to
//	convert a string of characters into a time value, in milliseconds.
//
//  (1) BOOL convertTimeStringToULONG32(
//		_CHAR* pTimeBuf,
//		ULONG32 timeBufLen, 
//		ULONG32& timeValInMillisec);
//	Converts a string, like "0:00:02.341", into a ULONG32 "time" value,
//  	in milliseconds, and returns FALSE, with timeValInMillisec
//	undefined if pTimeBuf is not in the correct time format which is:
//	"[[[[[[d:]h]h:]m]m:]s]s[.a[b[c]]]" where d is any number of days
//	up to 49 days (which is the max that 32 bits can hold, in msec),
//	hh is the number of hours (a two-digit # if following a ':'),
//	mm is the number of minutes (a two-digit # if following a ':'),
//	ss is the number of seconds (a two-digit # if following a ':'),
//	(noting that the lowest digit of seconds must exist in the
//	string and can stand alone as a time value), and
//	a, b, and c are tenths of seconds, hundredths of seconds, and
//	thousandths of seconds, respectively.
//	timeBufLen is equivalent to strlen(pTimeBuffer), i.e.,
//	it does not take into account the terminating '\0' char.
//
//	Returned is FALSE with timeValInMillisec undefined if error in
//	expected format is found.  Also, the pTimeBuf's contents can be
//	changed by this function (with '\0's where '.' and ':'s used to
//	be, but length of pTimeBuf is guaranteed to stay the same.
//
//  (2) BOOL IsTimeAMoreRecentThanTimeB(
//		ULONG32 ulTimeA, ULONG32 ulTimeB,
//		BOOL bIsLiveSource=TRUE,
//		ULONG32* pULTimeDiff=NULL /* OUT */,
//		ULONG32 ulAcceptableMaxTimeDiff=
//			    MAX_ALLOWED_TIME_DIFFERENCE_IN_MSEC)
//	If bIsLiveSource is FALSE (defaultable to TRUE), this simply
//	returns (A>B), else it's live & ULONG32 wrap-around can occur so...
//	this function tells whether or not time A is later (more recent)
//	than time B even with ULONG32 wrap-around, e.g., if A is 1234
//	and B is 4000001234, then we can guess that A is actually more
//	recent than B because A<B and B-A>ulAcceptableMaxTimeDiff,
//	so it looks like the clock wrapped around after B and before A.
//	Conversely, if A>B and A-B>ulAcceptableMaxTimeDiff, then it looks
//	like the clock wrapped around after A and before B, so A is NOT
//	more recent.  Returned is a BOOL that contains the answer.
//	NOTE: there is a concept of "infinity", defined as
//	TIME_INFINITY (which is 0xfffffffe), and there is a concept
//	of invalid time, defined as TIME_INVALID (0xffffffff).  The following
//	chart shows how these values are handled:
//	    A is:		B is:		return value will be:
//	    -----		-----		---------------------
//	    Infinity		Infinity	FALSE
//	    Infinity		Invalid		FALSE
//	    Infinity		< 0xfffffffe	TRUE
//	    Invalid		Infinity	TRUE
//	    Invalid		Invalid		FALSE
//	    Invalid		< 0xfffffffe	TRUE
//	    < 0xfffffffe	Infinity	FALSE
//	    < 0xfffffffe	Invalid		FALSE
//	    < 0xfffffffe	< 0xfffffffe	depends; see above algorithm
//
//	If pULTimeDiff is sent in as NULL, it remains NULL, otherwise it will
//	exit this function containing A minus B, regardless of which is
//	greater or more recent, noting that A & B are ULONG32s so the result
//	is always the equivalent of adding 0x100000000 to A and then
//	subtracting B and then truncating it by removing that 33rd bit, if
//	still 1:
//
//  (3) BOOL IsTimeASameOrMoreRecentThanTimeB(
//		ULONG32 ulTimeA, ULONG32 ulTimeB,
//		BOOL bIsLiveSource=TRUE,
//		ULONG32* pULTimeDiff=NULL /* OUT */,
//		ULONG32 ulAcceptableMaxTimeDiff=
//			    MAX_ALLOWED_TIME_DIFFERENCE_IN_MSEC)
//	This function first checks if time A is == to time B, and, if not
//	returns the return value from a call to (2), above.
//
//


#include "hxtypes.h"
#include "hxassert.h"
#include "rt_types.h" //for _CHAR

#include <stdlib.h>
#include <ctype.h>

#include "atotime.h"

#include "hxheap.h"
#ifdef _DEBUG
#undef HX_THIS_FILE		
static char HX_THIS_FILE[] = __FILE__;
#endif


#define NUM_DECIMAL_DIGITS_OF_SECONDS	3

BOOL convertTimeStringToULONG32(_CHAR* pTimeBuf, ULONG32 timeBufLen, 
	ULONG32& timeValInMillisec)
{
    _CHAR* pTimeBuffer = pTimeBuf;
    ULONG32 timeBufferLen = timeBufLen;

    // /Fixes PR 43536:  get rid of leading white spaces now; logic below
    // counts on no leading spaces:
    if (pTimeBuffer  &&  timeBufferLen)
    {
	while (' ' == *pTimeBuffer  &&  timeBufferLen)
	{
	    pTimeBuffer++;
	    timeBufferLen--;
	}
    }



    _CHAR savedEndChar = '\0';	//for restoring '\"' char at end, if found.

    ULONG32 days_, hours_, minutes_, seconds_, milliseconds_;
    days_ = hours_ = minutes_ = seconds_ = milliseconds_ = 0L;

    LONG32 bufIndx=0L;

    BOOL bDotEncounteredAlready = FALSE;
    LONG32 indexOfDot = -1;
    BOOL endCharWasChanged = FALSE;

    timeValInMillisec=0;

    HX_ASSERT_VALID_PTR(pTimeBuffer);
    HX_ASSERT(MIN_TIMEBUFFERLENGTH >= 1);
    if(!pTimeBuffer  ||  MIN_TIMEBUFFERLENGTH > timeBufferLen)
    {
	return FALSE;
    }

    savedEndChar = pTimeBuffer[timeBufferLen-1];

    //Get rid of start & terminating quotation mark, if they exist:
    if('\"' == pTimeBuffer[0])
    {
	pTimeBuffer++;
	timeBufferLen--;
	//Added this check to kill bug if (pTimeBuffer==")
	// and got shortened to an empty string:
	if(!timeBufferLen)
	{
	    return FALSE;
	}
    }
    if('\"' == pTimeBuffer[timeBufferLen-1])
    {
	pTimeBuffer[timeBufferLen-1] = '\0'; //get rid of end '\"'.
	timeBufferLen--;
	endCharWasChanged = TRUE;
    }
    
    //Work from right to left, searching first for milliseconds and then for
    //	seconds (or seconds only if no '.' found):
    BOOL bColonWasFound = FALSE;
    for(bufIndx=timeBufferLen-1; 0L<=bufIndx; bufIndx--)
    {
	_CHAR ch = toupper(pTimeBuffer[bufIndx]);
	if('0' > ch  ||  '9' < ch)
	{
	    if(' '==ch  ||  '\t'==ch  ||  '\n'==ch  ||  '\r'==ch)
	    {
		//Added everything up to "break;" to
		// handle (valid) strings with leading space(s) like " 39":
		//previous found was seconds_, so translate into ULONG:
		seconds_ = atol(&pTimeBuffer[bufIndx+1L]);
		timeValInMillisec += seconds_*1000; //converts seconds to ms.
		break; //we're done; we found seconds only.
	    }
	    else if('.' == ch)
	    {
		if(bDotEncounteredAlready)
		{
		    //Make sure pTimeBuffer is in original state:
		    if(endCharWasChanged)
		    {
			timeBufferLen++;
			pTimeBuffer[timeBufferLen-1] = savedEndChar;
		    }
		    if(indexOfDot >= 0)
		    {
			pTimeBuffer[indexOfDot] = '.';
		    }
		    //this second '.' is unexpected, so return with
		    //  timeValInMillisec set to whatever was read so far:
		    return FALSE;
		}

		bDotEncounteredAlready = TRUE;
		indexOfDot = bufIndx;
		pTimeBuffer[bufIndx] = '\0'; //end the buffr at the '.' .

		//previously-read #'s are milliseconds, so count them:
		//added "-1" to fix bug if buf ends with ".":
		if(1L > timeBufferLen-bufIndx-1) 
		{
		    milliseconds_ = 0L;
		}
		else
		{
		    //Now, make sure that more than three digits (base 10)
		    //	are not present, e.g., reduce "46371" to "463" since
		    //	we only allow millisecond precision (3 digits past
		    //	the decimal point:
		    _CHAR chTmp = '\0';
		    ULONG32 ulNumDecimalDigitsFound = timeBufferLen-1 - bufIndx;
		    if(NUM_DECIMAL_DIGITS_OF_SECONDS <
			    ulNumDecimalDigitsFound)
		    {
			chTmp = pTimeBuffer[bufIndx+1L];
			pTimeBuffer[bufIndx+NUM_DECIMAL_DIGITS_OF_SECONDS+1]=
				'\0';
		    }
		    milliseconds_ = atol(&pTimeBuffer[bufIndx+1L]);
		    //Added this to fix "y.x" being converted
		    // to y00x instead of yx00 milliseconds:
		    if(ulNumDecimalDigitsFound < NUM_DECIMAL_DIGITS_OF_SECONDS)
		    {
			for(ULONG32 ulDiff=NUM_DECIMAL_DIGITS_OF_SECONDS
				-ulNumDecimalDigitsFound; ulDiff>0; ulDiff--)
			{
			    milliseconds_ *= 10;
			}
		    }

		    if(NUM_DECIMAL_DIGITS_OF_SECONDS <
			    ulNumDecimalDigitsFound)
		    {
			//restore the changed char in the pTimeBuffer:
			pTimeBuffer[
				bufIndx+NUM_DECIMAL_DIGITS_OF_SECONDS+1]=
				chTmp;
		    }
		}
		
		timeValInMillisec = milliseconds_;
	    } //end "else if('.' == ch)".
	    else if(':' == ch)
	    {
		bColonWasFound = TRUE;
		//previous found was seconds_, so translate into ULONG:
		seconds_ = atol(&pTimeBuffer[bufIndx+1L]);
		timeValInMillisec += seconds_*1000; //converts seconds to ms.
		break; //done with "seconds_[.milliseconds_]" part.
	    }
	    else  //unexpected char found, so quit parsing:
	    {
		//Make sure pTimeBuffer is in original state:
		if(endCharWasChanged)
		{
		    timeBufferLen++;
		    pTimeBuffer[timeBufferLen-1] = savedEndChar;
		}
		if(indexOfDot >= 0)
		{
		    pTimeBuffer[indexOfDot] = '.';
		}
		//this char is unexpected, so return FALSE with
		//  timeValInMillisec set to whatever was read so far:
		return FALSE;
	    }
	} //end of "ch is a non-number" condition.
	else if(0L == bufIndx) //we're done with the buffer:
	{
	    //previous found was seconds_, so translate into ULONG:
	    seconds_ = atol(pTimeBuffer);
	    timeValInMillisec += seconds_*1000; //converts seconds to ms.
	    break; //done with "seconds_[.milliseconds_]" part.
	}
    } //end "for(bufIndx=timeBufferLen-1; ...".

    if(bColonWasFound) //then get the "minutes" part:
    {
	bColonWasFound = FALSE;
	//We've got the ":seconds.msecs" part, so lets get the hours part:
	for(bufIndx--; 0L<=bufIndx; bufIndx--)
	{
	    _CHAR ch = toupper(pTimeBuffer[bufIndx]);
	    if('0' > ch  ||  '9' < ch)
	    {
		if(' ' == ch  ||  '.' == ch)
		{
		    break;
		}
		else if(':' == ch)
		{
		    bColonWasFound = TRUE;
		    //previous found was seconds_, so translate into ULONG:
		    // (Note: this will do atol("min:sec") which ignores
		    // everything at & beyond the first non-num (":") char):
		    minutes_ = atol(&pTimeBuffer[bufIndx+1L]);
		    timeValInMillisec += minutes_*60000; //minutes to msec
		    break; //done w/ "minutes_:seconds_[milliseconds_]" part.
		}
		else  //unexpected char found, so quit parsing:
		{
		    //Make sure pTimeBuffer is in original state:
		    if(endCharWasChanged)
		    {
			timeBufferLen++;
			pTimeBuffer[timeBufferLen-1] = savedEndChar;
		    }
		    if(indexOfDot >= 0)
		    {
			pTimeBuffer[indexOfDot] = '.';
		    }
		    //this char is unexpected, so return FALSE with
		    //  timeValInMillisec set to whatever was read so far:
		    return FALSE;
		}
	    } //end of "ch is a non-number" condition.
	    else if(0L == bufIndx) //we're done with the buffer:
	    {
		//previous found was seconds_, so translate into ULONG:
		minutes_ = atol(pTimeBuffer);
		timeValInMillisec += minutes_*60000; //minutes to msec
		break; //done w/ "minutes_:seconds_[milliseconds_]" part.
	    }
	} //end "for(; ...".
    } //end "if(bColonWasFound) //then get the "minutes" part:".
    if(bColonWasFound) //then get the "hours" part:
    {
	bColonWasFound = FALSE;
	//We've got the ":minutes.seconds.msec" part, so lets get the hours:
	for(bufIndx--; 0L<=bufIndx; bufIndx--)
	{
	    _CHAR ch = toupper(pTimeBuffer[bufIndx]);
	    if('0' > ch  ||  '9' < ch)
	    {
		if(' ' == ch  ||  '.' == ch)
		{
		    break;
		}
		else if(':' == ch)
		{
		    bColonWasFound = TRUE;
		    //previous found was minutes_, so translate into ULONG:
		    // (Note: this will do atol("hrs:min:sec") which ignores
		    // everything at & beyond the first non-num (":") char):
		    hours_ = atol(&pTimeBuffer[bufIndx+1L]);
		    timeValInMillisec += hours_*3600000; //hours to msec
		    break;//done w/ "hours_:minutes_:seconds_[milliseconds_]"
		}
		else  //unexpected char found, so quit parsing:
		{
		    //Make sure pTimeBuffer is in original state:
		    if(endCharWasChanged)
		    {
			timeBufferLen++;
			pTimeBuffer[timeBufferLen-1] = savedEndChar;
		    }
		    if(indexOfDot >= 0)
		    {
			pTimeBuffer[indexOfDot] = '.';
		    }
		    //this char is unexpected, so return FALSE with
		    //  timeValInMillisec set to whatever was read so far:
		    return FALSE;
		}
	    } //end of "ch is a non-number" condition.
	    else if(0L == bufIndx) //we're done with the buffer:
	    {
		//previous found was seconds_, so translate into ULONG:
		hours_ = atol(pTimeBuffer);
		timeValInMillisec += hours_*3600000; //hours to msec
		break; //done w/ "hours_:minutes_:seconds_[milliseconds_]".
	    }
	} //end "for(; ...".
    } //end "if(bColonWasFound) //then get the "hours" part:".
    if(bColonWasFound) //then get the "days" part:
    {
	bColonWasFound = FALSE;
	//We've got the "hours:minutes.seconds.msec" part, so lets get the days:
	for(bufIndx--; 0L<=bufIndx; bufIndx--)
	{
	    _CHAR ch = toupper(pTimeBuffer[bufIndx]);
	    if('0' > ch  ||  '9' < ch)
	    {
		if(' ' == ch  ||  '.' == ch)
		{
		    break;
		}
		else if(':' == ch)
		{
		    bColonWasFound = TRUE;
		    //previous found was minutes_, so translate into ULONG:
		    // (Note: this will do atol("hrs:min:sec") which ignores
		    // everything at & beyond the first non-num (":") char):
		    days_ = atol(&pTimeBuffer[bufIndx+1L]);
		    timeValInMillisec += days_*86400000; //days to msec
		    break;//done w/ "days_:hours_:minutes_:seconds_[msecs_]"
		}
		else  //unexpected char found, so quit parsing:
		{
		    //Make sure pTimeBuffer is in original state:
		    if(endCharWasChanged)
		    {
			timeBufferLen++;
			pTimeBuffer[timeBufferLen-1] = savedEndChar;
		    }
		    if(indexOfDot >= 0)
		    {
			pTimeBuffer[indexOfDot] = '.';
		    }
		    //this char is unexpected, so return FALSE with
		    //  timeValInMillisec set to whatever was read so far:
		    return FALSE;
		}
	    } //end of "ch is a non-number" condition.
	    else if(0L == bufIndx) //we're done with the buffer:
	    {
		//previous found was seconds_, so translate into ULONG:
		hours_ = atol(pTimeBuffer);
		timeValInMillisec += hours_*86400000; //days to msec
		break; //done w/ "days_:hours_:minutes_:seconds_[msec_]".
	    }
	} //end "for(; ...".
    } //end "if(bColonWasFound ... "days" part:".

    if(endCharWasChanged)
    {
	timeBufferLen++;
	//Restore the orignial pTimeBuffer, in case end quote char was removed:
	pTimeBuffer[timeBufferLen-1] = savedEndChar;
    }
    
    if(indexOfDot >= 0)
    {
        pTimeBuffer[indexOfDot] = '.';
    }

    return TRUE;

} //end convertTimeStringToULONG32() function body.




//If bIsLiveSource is FALSE (defaultable to TRUE), this simply
// returns (A>B), else it's live & ULONG32 wrap-around can occur so...
// this function tells whether or not time A is later (more recent)
// than time B even with ULONG32 wrap-around, e.g., if A is 1234
// and B is 4000001234, then we can guess that A is actually more
// recent than B because A<B and B-A>ulAcceptableMaxTimeDiff,
// so it looks like the clock wrapped around after B and before A.
// Conversely, if A>B and A-B>ulAcceptableMaxTimeDiff, then it looks
// like the clock wrapped around after A and before B, so A is NOT
// more recent.  Returned is a BOOL that contains the answer.
// NOTE: there is a concept of "infinity", defined as
// TIME_INFINITY (which is 0xfffffffe), and there is a concept
// of invalid time, defined as TIME_INVALID (0xffffffff).  The following
// chart shows how these values are handled:
//	    A is:		B is:		return value will be:
//	    -----		-----		---------------------
//	    Infinity		Infinity	FALSE
//	    Infinity		Invalid		FALSE
//	    Infinity		< 0xfffffffe	TRUE
//	    Invalid		Infinity	TRUE
//	    Invalid		Invalid		FALSE
//	    Invalid		< 0xfffffffe	TRUE
//	    < 0xfffffffe	Infinity	FALSE
//	    < 0xfffffffe	Invalid		FALSE
//	    < 0xfffffffe	< 0xfffffffe	depends; see above algorithm
//
// If pULTimeDiff is sent in as NULL, it remains NULL, otherwise it will
// exit this function containing A minus B, regardless of which is
// greater or more recent, noting that A & B are ULONG32s so the result
// is always the equivalent of adding 0x100000000 to A and then
// subtracting B and then truncating it by removing that 33rd bit, if
// still 1:
BOOL
IsTimeAMoreRecentThanTimeB(
	ULONG32 ulTimeA, ULONG32 ulTimeB,
	//This is defaultable to TRUE (so assumes isLive if missing):
	BOOL bIsLiveSource,
	//This is defaultable to NULL:
	ULONG32* pULTimeDiff /* OUT */,
	//This is defaultable to MAX_ALLOWED_TIME_DIFFERENCE_IN_MSEC:
	ULONG32 ulAcceptableMaxTimeDiff)
{
    ULONG32 ulTimeDiff = ulTimeA-ulTimeB;
    BOOL bAIsMoreRecent = FALSE;

    if(pULTimeDiff)
    {
	*pULTimeDiff = ulTimeDiff;
    }

    //If we're not live, just return a straight comparison, assuming that
    // the timeline for non-live begins at 0:
    if(!bIsLiveSource)
    {
	return (ulTimeA > ulTimeB);
    }

    //(In)sanity check:
    HX_ASSERT(ulTimeDiff == ulTimeA + (0xFFFFFFFF-ulTimeB + 1L)); 
    if(TIME_INFINITY == ulTimeA)
    {
	if(TIME_INFINITY == ulTimeB  ||  TIME_INVALID == ulTimeB)
	{
	    bAIsMoreRecent = FALSE;
	}
	else
	{
	    bAIsMoreRecent = TRUE;
	}
    }
    else if(TIME_INVALID == ulTimeA)
    {
	if(TIME_INVALID == ulTimeB)
	{
	    bAIsMoreRecent = FALSE;
	}
	else
	{
	    bAIsMoreRecent = TRUE;
	}
    }
    else if(TIME_INFINITY == ulTimeB  ||  TIME_INVALID == ulTimeB)
    {
	bAIsMoreRecent = FALSE;
    }
    //else both A and B are neither infinite nor invalid:
    else if(ulTimeDiff > 0L  &&  ulTimeDiff < ulAcceptableMaxTimeDiff)
    {
	bAIsMoreRecent = TRUE;
    }
    else
    {
        bAIsMoreRecent = FALSE;
    }

    return bAIsMoreRecent;
}

BOOL
IsTimeASameOrMoreRecentThanTimeB(
	ULONG32 ulTimeA, ULONG32 ulTimeB,
	//This is defaultable to TRUE (so assumes isLive if missing):
	BOOL bIsLiveSource,
	//This is defaultable to NULL:
	ULONG32* pULTimeDiff /* OUT */,
	//This is defaultable to MAX_ALLOWED_TIME_DIFFERENCE_IN_MSEC:
	ULONG32 ulAcceptableMaxTimeDiff)
{
    if(ulTimeA == ulTimeB)
    {
	if(pULTimeDiff)
	{
	    *pULTimeDiff = ulTimeA-ulTimeB;
	}
	return TRUE;
    }
    else
    {
	return(IsTimeAMoreRecentThanTimeB(ulTimeA, ulTimeB,
		bIsLiveSource,
		pULTimeDiff,
		ulAcceptableMaxTimeDiff) );
    }
}
