<?php

/*
 * Copyright 2004-2017, AfterLogic Corp.
 * Licensed under AGPLv3 license or AfterLogic license
 * if commercial version of the product was purchased.
 * See the LICENSE file for a full license statement.
 */

namespace MailSo\Base;

/**
 * @category MailSo
 * @package Base
 */
class DateTimeHelper
{
	/**
	 * @access private
	 */
	private function __construct()
	{
	}

	/**
	 * @staticvar \DateTimeZone $oDateTimeZone
	 *
	 * @return \DateTimeZone
	 */
	public static function GetUtcTimeZoneObject()
	{
		static $oDateTimeZone = null;
		if (null === $oDateTimeZone)
		{
			$oDateTimeZone = new \DateTimeZone('UTC');
		}
		return $oDateTimeZone;
	}

	/**
	 * Parse date string formated as "Thu, 10 Jun 2010 08:58:33 -0700 (PDT)"
	 * RFC2822
	 *
	 * @param string $sDateTime
	 *
	 * @return int
	 */
	public static function ParseRFC2822DateString($sDateTime)
	{
		$sFormat = 'D, d M Y H:i:s O';
		if (\version_compare(\PHP_VERSION, '5.3.9') >= 0)
		{
			$sFormat .= '+';
		}
		$sDateTime = \trim(\preg_replace('/ \([a-zA-Z0-9]+\)$/', '', \trim($sDateTime)));
		$oDateTime = \DateTime::createFromFormat($sFormat, $sDateTime, \MailSo\Base\DateTimeHelper::GetUtcTimeZoneObject());
		return $oDateTime ? $oDateTime->getTimestamp() : 0;
	}

	/**
	 * Parse date string formated as "10-Jan-2012 01:58:17 -0800"
	 * IMAP INTERNALDATE Format
	 *
	 * @param string $sDateTime
	 *
	 * @return int
	 */
	public static function ParseInternalDateString($sDateTime)
	{
		$sDateTime = \trim($sDateTime);
		if (\preg_match('/^[a-z]{2,4}, /i', $sDateTime)) // RFC2822
		{
			return \MailSo\Base\DateTimeHelper::ParseRFC2822DateString($sDateTime);
		}
		$sFormat = 'd-M-Y H:i:s O';
		if (\version_compare(\PHP_VERSION, '5.3.9')  >= 0)
		{
			$sFormat .= '+';
		}
		$oDateTime = \DateTime::createFromFormat($sFormat, $sDateTime, \MailSo\Base\DateTimeHelper::GetUtcTimeZoneObject());
		return $oDateTime ? $oDateTime->getTimestamp() : 0;
	}

	/**
	 * Parse date string formated as "2011-06-14 23:59:59 +0400"
	 *
	 * @param string $sDateTime
	 *
	 * @return int
	 */
	public static function ParseDateStringType1($sDateTime)
	{
		$sFormat = 'Y-m-d H:i:s O';
		if (\version_compare(\PHP_VERSION, '5.3.9')  >= 0)
		{
			$sFormat .= '+';
		}
		$oDateTime = \DateTime::createFromFormat($sFormat, \trim($sDateTime), \MailSo\Base\DateTimeHelper::GetUtcTimeZoneObject());
		return $oDateTime ? $oDateTime->getTimestamp() : 0;
	}
}
