/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

using System;

namespace Lucene.Net.Documents
{
	
	/// <summary> Provides support for converting dates to strings and vice-versa.
	/// The strings are structured so that lexicographic sorting orders 
	/// them by date, which makes them suitable for use as field values 
	/// and search terms.
	/// 
	/// <P>This class also helps you to limit the resolution of your dates. Do not
	/// save dates with a finer resolution than you really need, as then
	/// RangeQuery and PrefixQuery will require more memory and become slower.
	/// 
	/// <P>Compared to {@link DateField} the strings generated by the methods
	/// in this class take slightly more space, unless your selected resolution
	/// is set to <code>Resolution.DAY</code> or lower.
	/// </summary>
	public class DateTools
	{
		
		private DateTools()
		{
		}
		
		/// <summary> Converts a Date to a string suitable for indexing.
		/// 
		/// </summary>
		/// <param name="date">the date to be converted
		/// </param>
		/// <param name="resolution">the desired resolution, see
		/// {@link #Round(Date, DateTools.Resolution)}
		/// </param>
		/// <returns> a string in format <code>yyyyMMddHHmmssSSS</code> or shorter,
		/// depeding on <code>resolution</code>
		/// </returns>
		public static System.String DateToString(System.DateTime date, Resolution resolution)
		{
			return TimeToString(date.Ticks, resolution);
		}
		
		/// <summary> Converts a millisecond time to a string suitable for indexing.
		/// 
		/// </summary>
		/// <param name="time">the date expressed as milliseconds since January 1, 1970, 00:00:00 GMT
		/// </param>
		/// <param name="resolution">the desired resolution, see
		/// {@link #Round(long, DateTools.Resolution)}
		/// </param>
		/// <returns> a string in format <code>yyyyMMddHHmmssSSS</code> or shorter,
		/// depeding on <code>resolution</code>; using UTC as timezone
		/// </returns>
		public static System.String TimeToString(long time, Resolution resolution)
		{
			System.Globalization.Calendar cal = new System.Globalization.GregorianCalendar(); // {{Aroush}} do we care about 'cal'
			
			//protected in JDK's prior to 1.4
			//cal.setTimeInMillis(round(time, resolution));
			
			System.DateTime dt = new System.DateTime(Round(time, resolution));

			System.String t = "";

            if (resolution == Resolution.YEAR)
            {
                t = dt.ToString("yyyy");
            }
            else if (resolution == Resolution.MONTH)
            {
                t = dt.ToString("yyyyMM");
            }
            else if (resolution == Resolution.DAY)
            {
                t = dt.ToString("yyyyMMdd");
            }
            else if (resolution == Resolution.HOUR)
            {
                t = dt.ToString("yyyyMMddHH");
            }
            else if (resolution == Resolution.MINUTE)
            {
                t = dt.ToString("yyyyMMddHHmm");
            }
            else if (resolution == Resolution.SECOND)
            {
                t = dt.ToString("yyyyMMddHHmmss");
            }
            else if (resolution == Resolution.MILLISECOND)
            {
                t = dt.ToString("yyyyMMddHHmmssfff");
            }
            else
            {
                throw new System.ArgumentException("unknown resolution " + resolution);
            }

            return t;
		}
		
		/// <summary> Converts a string produced by <code>timeToString</code> or
		/// <code>DateToString</code> back to a time, represented as the
		/// number of milliseconds since January 1, 1970, 00:00:00 GMT.
		/// 
		/// </summary>
		/// <param name="dateString">the date string to be converted
		/// </param>
		/// <returns> the number of milliseconds since January 1, 1970, 00:00:00 GMT
		/// </returns>
		/// <throws>  ParseException if <code>dateString</code> is not in the  </throws>
		/// <summary>  expected format 
		/// </summary>
		public static long StringToTime(System.String dateString)
		{
			return StringToDate(dateString).Ticks;
		}
		
		/// <summary> Converts a string produced by <code>timeToString</code> or
		/// <code>DateToString</code> back to a time, represented as a
		/// Date object.
		/// 
		/// </summary>
		/// <param name="dateString">the date string to be converted
		/// </param>
		/// <returns> the parsed time as a Date object 
		/// </returns>
		/// <throws>  ParseException if <code>dateString</code> is not in the  </throws>
		/// <summary>  expected format 
		/// </summary>
		public static System.DateTime StringToDate(System.String dateString)
		{
            System.String yyyy = "1";
            System.String MM = "1";
            System.String dd = "1";
            System.String HH = "0";
            System.String mm = "0";
            System.String ss = "0";
            System.String SSS = "0";

            if (dateString.Length == 4)     // "yyyy"
            {
                yyyy = dateString.Substring(0, 4);
            }
            else if (dateString.Length == 6)     // "yyyyMM";
            {
                yyyy = dateString.Substring(0, 4);
                MM = dateString.Substring(4, 2);
            }
            else if (dateString.Length == 8)     // "yyyyMMdd"
            {
                yyyy = dateString.Substring(0, 4);
                MM = dateString.Substring(4, 2);
                dd = dateString.Substring(6, 2);
            }
            else if (dateString.Length == 10)    // "yyyyMMddHH"
            {
                yyyy = dateString.Substring(0, 4);
                MM = dateString.Substring(4, 2);
                dd = dateString.Substring(6, 2);
                HH = dateString.Substring(8, 2);
            }
            else if (dateString.Length == 12)    // "yyyyMMddHHmm";
            {
                yyyy = dateString.Substring(0, 4);
                MM = dateString.Substring(4, 2);
                dd = dateString.Substring(6, 2);
                HH = dateString.Substring(8, 2);
                mm = dateString.Substring(10, 2);
            }
            else if (dateString.Length == 14)    // "yyyyMMddHHmmss";
            {
                yyyy = dateString.Substring(0, 4);
                MM = dateString.Substring(4, 2);
                dd = dateString.Substring(6, 2);
                HH = dateString.Substring(8, 2);
                mm = dateString.Substring(10, 2);
                ss = dateString.Substring(12, 2);
            }
            else if (dateString.Length == 17)    // "yyyyMMddHHmmssSSS";
            {
                yyyy = dateString.Substring(0, 4);
                MM = dateString.Substring(4, 2);
                dd = dateString.Substring(6, 2);
                HH = dateString.Substring(8, 2);
                mm = dateString.Substring(10, 2);
                ss = dateString.Substring(12, 2);
                SSS = dateString.Substring(14, 3);
            }
            else
            {
                throw new System.FormatException("Input is not valid date string: " + dateString);
            }

            int y, M, d, H, m, s, S;
            y = Convert.ToInt16(yyyy);
            M = Convert.ToInt16(MM);
            d = Convert.ToInt16(dd);
            H = Convert.ToInt16(HH);
            m = Convert.ToInt16(mm);
            s = Convert.ToInt16(ss);
            S = Convert.ToInt16(SSS);

            return new System.DateTime(y, 
                M, d, H, 
                m, s, S);

            //return new System.DateTime(Convert.ToInt16(yyyy), 
            //    Convert.ToInt16(MM), Convert.ToInt16(dd), Convert.ToInt16(HH), 
            //    Convert.ToInt16(mm), Convert.ToInt16(ss), Convert.ToInt16(SSS));
        }
		
		/// <summary> Limit a date's resolution. For example, the date <code>2004-09-21 13:50:11</code>
		/// will be changed to <code>2004-09-01 00:00:00</code> when using
		/// <code>Resolution.MONTH</code>. 
		/// 
		/// </summary>
		/// <param name="resolution">The desired resolution of the date to be returned
		/// </param>
		/// <returns> the date with all values more precise than <code>resolution</code>
		/// set to 0 or 1
		/// </returns>
        public static System.DateTime Round(System.DateTime date, Resolution resolution)
        {
            return new System.DateTime(Round(date.Ticks, resolution));
        }
		
		/// <summary> Limit a date's resolution. For example, the date <code>1095767411000</code>
		/// (which represents 2004-09-21 13:50:11) will be changed to 
		/// <code>1093989600000</code> (2004-09-01 00:00:00) when using
		/// <code>Resolution.MONTH</code>.
		/// 
		/// </summary>
		/// <param name="resolution">The desired resolution of the date to be returned
		/// </param>
		/// <returns> the date with all values more precise than <code>resolution</code>
		/// set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT
		/// </returns>
        public static long Round(long time, Resolution resolution)
        {
            System.Globalization.Calendar cal = new System.Globalization.GregorianCalendar(); // {{Aroush}} do we care about 'cal'
			
            // protected in JDK's prior to 1.4
            //cal.setTimeInMillis(time);
			
            System.DateTime dt = new System.DateTime(time);
			
            if (resolution == Resolution.YEAR)
            {
                dt = dt.AddMonths(1 - dt.Month);
                dt = dt.AddDays(1 - dt.Day);
                dt = dt.AddHours(0 - dt.Hour);
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.MONTH)
            {
                dt = dt.AddDays(1 - dt.Day);
                dt = dt.AddHours(0 - dt.Hour);
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.DAY)
            {
                dt = dt.AddHours(0 - dt.Hour);
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.HOUR)
            {
                dt = dt.AddMinutes(0 - dt.Minute);
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.MINUTE)
            {
                dt = dt.AddSeconds(0 - dt.Second);
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.SECOND)
            {
                dt = dt.AddMilliseconds(0 - dt.Millisecond);
            }
            else if (resolution == Resolution.MILLISECOND)
            {
                // don't cut off anything
            }
            else
            {
                throw new System.ArgumentException("unknown resolution " + resolution);
            }
            return dt.Ticks;
        }
		
        /// <summary>Specifies the time granularity. </summary>
        public class Resolution
		{
			public static readonly Resolution YEAR = new Resolution("year");
			public static readonly Resolution MONTH = new Resolution("month");
			public static readonly Resolution DAY = new Resolution("day");
			public static readonly Resolution HOUR = new Resolution("hour");
			public static readonly Resolution MINUTE = new Resolution("minute");
			public static readonly Resolution SECOND = new Resolution("second");
			public static readonly Resolution MILLISECOND = new Resolution("millisecond");
			
			private System.String resolution;
			
			internal Resolution()
			{
			}
			
			internal Resolution(System.String resolution)
			{
				this.resolution = resolution;
			}
			
			public override System.String ToString()
			{
				return resolution;
			}
		}
	}
}