/*<<<***************************************************************************
The MIT License (MIT)

Copyright(C) 2013 - 2015 Marc Mirti Mancinelli, Christophe Lardau and Philippe Pamart (xdcube.org)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
#Title: xbTypesAdv
#Project: xdcBase
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<12/02/2014: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
#include "stdafx.h"

#include "xbTypesAdv.h"

#define comcfgTIME_WEEKDAY \
	{"Monday", "Tuesday", "Wednesday", "Thursday", \
	"Friday", "Saturday", "Sunday"} 
#define comcfgTIME_MONTH \
	{"January", "February", "March", "April", \
	"May", "June", "July", "August", "September", \
	"October","November","December"} 

xbString comcfgTime::Get(comcfgTimeFormat frmt,LPCSTR pTZ,LPCSTR *ppDayNames,
						 LPCSTR *ppMonthNames) const
{
	xbString ret(GetDate(frmt,ppDayNames,ppMonthNames));

	if (m_hour >= 0 || m_min >= 0 || m_sec >= 0 || m_msec >= 0)
	{
		if (ret.IsValid())
			ret += ' ';
		ret += GetTime(pTZ);
	}

	return ret;
}

xbString comcfgTime::GetDate(comcfgTimeFormat frmt,LPCSTR *ppDayNames,LPCSTR *ppMonthNames) const
{
	static const char *_wdName[] = comcfgTIME_WEEKDAY;
	static const char *_mName[] = comcfgTIME_MONTH;

	if (!ppDayNames) 
		ppDayNames = _wdName;
	if (!ppMonthNames) 
		ppMonthNames = _mName;
	xbString ret;

	if (m_week >= 0 && frmt != comcfgTimeShort) 
	{
		if (frmt == comcfgTimeLong)
			ret += xbString(ppDayNames[m_week]) + ", ";
		else
			ret += xbString(ppDayNames[m_week],3) + ", ";
	}

	if (m_year >= 0 || m_month >= 0 || m_day >= 0)
	{
		if (frmt != comcfgTimeShort)
		{
			if (m_day > 0) 
			{
				if (frmt == comcfgTimeLong)
					ret += xbString(m_day)+' ';
				else
					ret += xbFormat("%02hd ",m_day);
			}
			else ret += "* ";
			if (m_month > 0) 
			{
				if (frmt == comcfgTimeLong)
					ret += xbString(ppMonthNames[m_month-1])+' ';
				else
					ret += xbString(ppMonthNames[m_month-1],3)+' ';
			}
			else ret += "* ";
		}
		else
		{
			if (m_day > 0) ret += xbFormat("%02hd/",m_day);
			else ret += "*/";
			if (m_month > 0) ret += xbFormat("%02hd/",m_month);
			else ret += "*/";
		}
		if (m_year > 0) ret += xbString(m_year);
		else ret += '*';
	}

	ret.Trim();
	return ret;
}

xbString comcfgTime::GetTime(LPCSTR pTZ) const
{
	xbString ret;

	if (m_hour >= 0 || m_min >= 0 || m_sec >= 0 || m_msec >= 0)
	{
		if (m_hour >= 0) 
			ret += xbFormat("%02hd:",m_hour);
		else 
			ret += "*:";
		if (m_min >= 0) 
			ret += xbFormat("%02hd",m_min);
		else 
			ret += "*";
		if (m_sec >= 0 || m_msec >= 0)
		{
			if (m_sec >= 0) 
				ret += xbFormat(":%02hd",m_sec);
			else 
				ret += "*";

			if (m_msec >= 0)
				ret += xbFormat(".%03hd",m_msec);
		}
		if (pTZ && *pTZ)
			ret += ' ' + xbString(pTZ);
	}

	return ret;
}

bool comcfgTime::Set(const xbString &val,xbString *pTZ,
					 LPCSTR *ppDayNames,LPCSTR *ppMonthNames,xbOpMode opm)
{
	static const char *_wdName[] = comcfgTIME_WEEKDAY;
	static const char *_mName[] = comcfgTIME_MONTH;

	Init(-2);
	xbString str;
	int pos = 0;
	char chSep = 0,curChSep = 0,lastChSep = 0;
	while((pos = val.GetToken(pos," \t,-:/",&str,NULL,&chSep)) > 0)
	{
		lastChSep = curChSep;
		curChSep = chSep;
		if (str.IsEmpty()) 
			continue;
		if (str == "*")
		{
			short *pNb;
			if (lastChSep == ':' || curChSep == ':')
			{
				if (m_hour < -1)
					pNb = &m_hour;
				else if (m_min < -1)
					pNb = &m_min;
				else
				{
					if (m_sec >= -1)
					{
						if (opm == xbOp_Optional) return false;
						xbThrow xbEappCfg("Invalid Time : '"+val+"', bad time (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], HH:MM:SS incorrect, character position="+xbString(pos)+":*)");
					}
					pNb = &m_sec;
				}
				*pNb = -1;
				continue;
			}
			if (m_day < -1)
				pNb = &m_day;
			else if (m_month < -1)
				pNb = &m_month;
			else
			{
				if (m_year >= -1)
				{
					if (opm == xbOp_Optional) return false;
					xbThrow xbEappCfg("Invalid Time : '"+val+"', bad date (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], DD MMM YYYY incorrect, character position="+xbString(pos)+":*)");
				}
				pNb = &m_year;
			}
			*pNb = -1;
			continue;
		}
		if (str.First() >= '0' && str.First() <= '9')
		{
			short *pNb;
			if (lastChSep == ':' || curChSep == ':')
			{
				if (m_hour < -1)
					pNb = &m_hour;
				else if (m_min < -1)
					pNb = &m_min;
				else
				{
					if (m_sec >= -1)
					{
						if (opm == xbOp_Optional) return false;
						xbThrow xbEappCfg("Invalid Time : '"+val+"', bad time (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], HH:MM:SS incorrect, character position="+xbString(pos)+":"+str+")");
					}
					 pNb = &m_sec;
				}

				char *ptr = NULL;
				int nval = strtol(str,&ptr,10);
				if ((ptr != NULL && *ptr != 0) || nval < 0)
				{
					if (opm == xbOp_Optional) return false;
					xbThrow xbEappCfg("Invalid Time : '"+val+"', bad time (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], HH:MM:SS incorrect, character position="+xbString(pos)+":"+str+")");
				}

				if (nval > 23 && pNb == &m_hour)
				{
					if (opm == xbOp_Optional) return false;
					xbThrow xbEappCfg("Invalid Time : '"+val+"' (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], HH incorrect, character position="+xbString(pos)+":"+str+")");
				}
				if (nval > 59)
				{
					if (opm == xbOp_Optional) return false;
					xbThrow xbEappCfg("Invalid Time : '"+val+"' (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], MM or SS incorrect, character position="+xbString(pos)+":"+str+")");
				}
				*pNb = nval;
				continue;
			}
			if (m_day < -1)
				pNb = &m_day;
			else if (m_month < -1)
				pNb = &m_month;
			else
			{
				 if (m_year >= -1)
				 {
					if (opm == xbOp_Optional) return false;
					xbThrow xbEappCfg("Invalid Time : '"+val+"', bad date (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], DD MMM YYYY incorrect, character position="+xbString(pos)+":"+str+")");
				 }
				 pNb = &m_year;
			}
			char *ptr = NULL;
			int nval = strtol(str,&ptr,10);
			if ((ptr != NULL && *ptr != 0) || nval < 0)
			{
				if (opm == xbOp_Optional) return false;
				xbThrow xbEappCfg("Invalid Time : '"+val+"', bad date (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], DD MMM YYYY incorrect, character position="+xbString(pos)+":"+str+")");
			}
			if ((nval >= 70 && m_year < -1) || pNb == &m_year) 
			{
				pNb = &m_year;
				if (nval < 200)
				{
					if (nval < 70)
						nval += 2000;
					else
						nval += 1900;
				}
			}
			else
			{
				if ((nval < 1 || nval > 31) && pNb == &m_day)
				{
					if (opm == xbOp_Optional) return false;
					xbThrow xbEappCfg("Invalid Time : '"+val+"' (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], DD incorrect, character position="+xbString(pos)+":"+str+")");
				}
				if ((nval < 1 || nval > 12) && pNb == &m_month)
				{
					if (opm == xbOp_Optional) return false;
					xbThrow xbEappCfg("Invalid Time : '"+val+"' (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], MMM incorrect, character position="+xbString(pos)+":"+str+")");
				}
			}

			*pNb = nval;
			continue;
		}
		int lg = str.Length;
		if (lg > 1)
		{
			const char **pDayName = ppDayNames;
			int no = 0;
			if (pDayName)
			{
				while(no < 7)
				{
					if (xbStrnicmp(*pDayName,str,lg) == 0)
					{
						if (m_week >= 0)
						{
							if (opm == xbOp_Optional) return false;
							xbThrow xbEappCfg("Invalid Time : '"+val+"', day of week seems to be defined more than one time (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], WeekDay incorrect, character position="+xbString(pos)+":"+str+")");
						}
						m_week = no;
						break;
					}
					no++;
					pDayName++;
				}
				if (no < 7)
					continue;
				no = 0;
			}
			pDayName = _wdName;
			while(no < 7)
			{
				if (xbStrnicmp(*pDayName,str,lg) == 0)
				{
					if (m_week >= 0)
					{
						if (opm == xbOp_Optional) return false;
						xbThrow xbEappCfg("Invalid Time : '"+val+"', day of week seems to be defined more than one time (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], WeekDay incorrect, character position="+xbString(pos)+":"+str+")");
					}
					m_week = no;
					break;
				}
				no++;
				pDayName++;
			}
			if (no < 7)
				continue;
		}
		if (lg > 1)
		{
			const char **pMonthName = ppMonthNames;
			int no = 0;
			if (pMonthName)
			{
				while(no < 12)
				{
					if (xbStrnicmp(*pMonthName,str,lg) == 0)
					{
						if (m_month >= -1)
						{
							if (opm == xbOp_Optional) return false;
							xbThrow xbEappCfg("Invalid Time : '"+val+"', month seems to be defined more than one time (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], MMM incorrect, character position="+xbString(pos)+":"+str+")");
						}
						m_month = no + 1;
						break;
					}
					no++;
					pMonthName++;
				}
				if (no < 12)
					continue;
				no = 0;
			}
			pMonthName = _mName;
			while(no < 12)
			{
				if (xbStrnicmp(*pMonthName,str,lg) == 0)
				{
					if (m_month >= -1)
					{
						if (opm == xbOp_Optional) return false;
						xbThrow xbEappCfg("Invalid Time : '"+val+"', month seems to be defined more than one time (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ], MMM incorrect, character position="+xbString(pos)+":"+str+")");
					}
					m_month = no + 1;
					break;
				}
				no++;
				pMonthName++;
			}
			if (no < 12)
				continue;
		}

		if ((pos>0 && pos <= val.Length) || (!pTZ && str.CompareNoCase("GMT") != 0 && str.CompareNoCase("UTC") != 0))
		{
			if (opm == xbOp_Optional) return false;
			xbThrow xbEappCfg("Invalid Time : '"+val+"', bad word '"+str+"' (Syntax: [WeekDay[,]] [DD MMM YYYY] [HH:MM:SS] [TZ])");
		}

		if (pTZ)
			*pTZ = str;
	}

	if (m_year >= 0
		&& m_month>= 0
		&& m_day>=0)
	{
		xbDateTime dt(m_year,m_month,m_day,0,0,0);

		if (dt.IsEmpty())
		{
			if (opm == xbOp_Optional) return false;
			xbThrow xbEappCfg("Invalid Time : '"+val+"', date doesn't exist (Syntax: [WeekDay] [YYYY/MM/DD] [HH:MM], YYYY/MM/DD incorrect)");
		}
	}
	return true;
}


comcfgTime comcfgTime::GetStartDate(const comcfgTime &ti) const
{	
	comcfgTime ret;
	bool bWC = true;
	if (m_year > 0 && m_year > ti.m_year)
	{
		ret.m_year = m_year;
		bWC = false;
	}
	else
		ret.m_year = ti.m_year;
	
	if (m_month > 0 && m_month > ti.m_month)
	{
		ret.m_month = m_month;
		bWC = false;
	}
	else
	{
		if (bWC)
			ret.m_month = ti.m_month;
		else
			ret.m_month = 1;
	}

	int mnd = xbDateTime::GetDaysOfMonth(ret.m_year,ret.m_month);
	if (m_day > 0 && m_day > ti.m_day)
	{
		ret.m_day = m_day;
		bWC = false;
		while (ret.m_day > mnd && ret.m_day <= 31)
		{
			ret.m_month++;
			if (ret.m_month > 12)
			{
				ret.m_month = 1;
				ret.m_year++;
			}
			mnd = xbDateTime::GetDaysOfMonth(ret.m_year,ret.m_month);
		}
	}
	else
	{
		if (bWC)
		{
			ret.m_day = ti.m_day;
			while (ret.m_day > mnd && ret.m_day <= 31)
			{
				ret.m_month++;
				if (ret.m_month > 12)
				{
					ret.m_month = 1;
					ret.m_year++;
				}
				mnd = xbDateTime::GetDaysOfMonth(ret.m_year,ret.m_month);
			}
		}
		else
			ret.m_day = 1;


		if (m_week >= 0)
		{
			xbDateTime dt;
			dt.SetDate(ret.m_year,ret.m_month,ret.m_day);
			int wk = dt.GetDayOfWeek();
			if (m_week > wk)
			{
				ret.m_day += m_week - wk;
			}
			else
			{
				ret.m_day += 7 - (wk - m_week);
			}
			if (ret.m_day > mnd)
			{
				ret.m_day -= mnd;
				ret.m_month++;
				if (ret.m_month > 12)
				{
					ret.m_month = 1;
					ret.m_year++;
				}
			}
		}
	}

	if (m_hour >= 0 && m_hour > ti.m_hour)
	{
		ret.m_hour = m_hour;
		bWC = false;
	}
	else
	{
		if (bWC)
			ret.m_hour = ti.m_hour;
		else
			ret.m_hour = 0;
	}

	if (m_min >= 0 && m_min > ti.m_min)
	{
		ret.m_min = m_min;
		bWC = false;
	}
	else
	{
		if (bWC)
			ret.m_min = ti.m_min;
		else
			ret.m_min = 0;
	}

	if (m_sec >= 0 && m_sec > ti.m_sec)
	{
		ret.m_sec = m_sec;
		bWC = false;
	}
	else
	{
		if (bWC)
			ret.m_sec = ti.m_sec;
		else
			ret.m_sec = 0;
	}

	return ret;
}

bool comcfgTime::GetNextDate(const comcfgTime &ti,xbDateTime *pNext) const
{	
	comcfgTime ret(ti);
	int mnd;
	for(;;)
	{
		if (m_year > 0 && ret.m_year > m_year)
			return false;
		
		if (m_month > 0 && ret.m_month > m_month)
		{
			ret.m_month = 1;
			ret.m_year++;
			goto adj_year;
		}

		if (m_day > 0 && ret.m_day > m_day)
		{
			ret.m_day = 1;
			ret.m_month++;
			goto adj_month;
		}
		if (m_day <= 0 && m_week >= 0 && ret.m_week > m_week)
		{
			ret.m_day += (7 - m_week);
			goto adj_day;
		}
		if (m_hour >= 0 && ret.m_hour > m_hour)
		{
			ret.m_hour = 0;
			ret.m_day++;
			goto adj_day;
		}
		if (m_min >= 0 && ret.m_min > m_min)
		{
			ret.m_min = 0;
			ret.m_hour++;
			goto adj_hour;
		}
		if (m_sec >= 0 && ret.m_sec > m_sec)
		{
			ret.m_sec = 0;
			ret.m_min++;
			goto adj_min;
		}
		break;
	adj_min:
		if (ret.m_min > 59)
		{
			ret.m_min -= 60;
			ret.m_hour++;
		}
	adj_hour:
		if (ret.m_hour > 23)
		{
			ret.m_min -= 24;
			ret.m_day++;
		}
	adj_day:
		mnd = xbDateTime::GetDaysOfMonth(ret.m_year,ret.m_month);
		if (ret.m_day > mnd)
		{
			ret.m_day -= mnd;
			ret.m_year++;
		}
	adj_month:
		if (ret.m_month > 12)
		{
			ret.m_month -= 12;
			ret.m_year++;
		}
	adj_year:
		{
			xbDateTime dt;
			dt.SetDate(ret.m_year,ret.m_month,ret.m_day);
			ret.m_week = dt.GetDayOfWeek();
		}
	}
	if (pNext)
		ret.ToDateTime(pNext);
	return true;
}

void comcfgTime::Init(const xbDateTime &dt)
{
	int y,mon,d;
	bool bDate = dt.HasDate();
	if (bDate)
	{
		if (!xbDateTime::dateFromDouble(dt,&y,&mon,&d))
			xbThrow xbEarg("Invalid date","comcfgTime::Init()");
	}
	else
	{
		y = mon = d = -1;
	}
	int h,min,s,ms;
	bool bTime = dt.HasTime();
	if (bTime)
	{
		if (!xbDateTime::timeFromDouble(dt,NULL,&h,&min,&s,&ms))
			xbThrow xbEarg("Invalid date","comcfgTime::Init()");
	}
	else
	{
		h = min = s = ms = -1;
	}

	m_week = bDate?dt.GetDayOfWeekMon():-1;
	m_year = y;
	m_month = mon;
	m_day = d;
	m_hour = h;
	m_min = min;
	m_sec = s;
	m_msec = ms;
}

void comcfgTime::ToDateTime(xbDateTime *pDt) const
{
	bool bDate = (m_year>=0 || m_month>=0 || m_day>=0);
	bool bTime = (m_hour>=0 || m_min>=0 || m_sec>=0 || m_msec>=0);

	if (bDate && bTime)
	{
		pDt->SetDateTime(m_year,m_month,m_day,m_hour,m_min,m_sec,m_msec);
		return;
	}
	if (bDate)
	{
		pDt->SetDate(m_year,m_month,m_day);
		return;
	}
	if (bTime)
	{
		pDt->SetTime(m_min,m_sec,m_msec);
		return;
	}

	pDt->Empty();
}

comcfgTime::operator xbDateTime() const
{
	xbDateTime dt;
	ToDateTime(&dt);
	return dt;
}
