using System;
using System.Text;
using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;

namespace Raytheon.Units
{
    /// <summary>
    /// This class represents a velocity.  
    /// 
    /// It has no constructors.  Instead, it provides multiple methods for creating objects of this 
    /// type.  Those methods are of the form FromXXX, where XXX is a unit (e.g. FromMetersPerSec).
    /// 
    /// Properties (e.g. FeetPerSec) are provided to convert the value to other units and return 
    /// as type double.
    /// 
    /// Methods (operator overloads) are provided to perform calculations with related types (e.g. 
    /// Acceleration, Length).
    /// </summary>
    [Serializable]
    [DataContract]
    public class Velocity
    {
        public enum Unit
        {
            FeetPerSecond,
            MetersPerSecond,
        }

        public static IDictionary<Unit, List<string>> UnitAbbreviations = new Dictionary<Unit, List<string>>()
        {
            {Unit.FeetPerSecond,   new List<string>(){ "ft/sec" } },
            {Unit.MetersPerSecond, new List<string>(){ "m/sec" } },
        };

        private const Unit DefaultUnits = Unit.MetersPerSecond;
        private const double FeetPerMeter = 3.280839895013123;

        [DataMember(Name = "Velocity", IsRequired = true)]
        private double _velocity; // meters/second

        // map: unit => abbreviation, conversion method and property
        private static IDictionary<Unit, UnitInfo<Velocity>> _unitInfo = new Dictionary<Unit, UnitInfo<Velocity>>()
        {
            { Unit.FeetPerSecond,   new UnitInfo<Velocity>(UnitAbbreviations[Unit.FeetPerSecond],   FromFeetPerSec,   typeof(Velocity).GetProperty("FeetPerSec").GetGetMethod()) },
            { Unit.MetersPerSecond, new UnitInfo<Velocity>(UnitAbbreviations[Unit.MetersPerSecond], FromMetersPerSec, typeof(Velocity).GetProperty("MetersPerSec").GetGetMethod()) },
        };

        /// <summary>
        /// Prevents a default instance of the <see cref="Velocity"/> class from being created.  
        /// Use FromXXX methods to create objects of this type.
        /// </summary>
        /// <exception cref="System.Exception">No one should be calling this, it is only here to prevent users from creating default object</exception>
        private Velocity()
        {
            throw new InvalidOperationException("No one should be calling this, it is only here to prevent users from creating default object");
        }

        /// <summary>
        /// ctor used by this class to create objects in FromXXX methods 
        /// </summary>
        /// <param name="velocity">The velocity - m/sec.</param>
        private Velocity(double velocity)
        {
            _velocity = velocity;
        }

        #region conversion properties

        /// <summary>
        /// Returns feet/sec as type double
        /// </summary>
        /// <value>
        /// feet/sec
        /// </value>
        public double FeetPerSec
        {
            get { return _velocity * FeetPerMeter; }
        }

        /// <summary>
        /// Returns meters/sec as type double
        /// </summary>
        /// <value>
        /// meters/sec
        /// </value>
        public double MetersPerSec
        {
            get { return _velocity; }
        }

        #endregion

        #region creation methods

        /// <summary>
        /// Returns Velocity object interpreting passed value as ft/sec
        /// </summary>
        /// <param name="feetPerSec">ft/sec</param>
        /// <returns></returns>
        public static Velocity FromFeetPerSec(double feetPerSec)
        {
            return new Velocity(feetPerSec / FeetPerMeter);
        }

        /// <summary>
        /// Returns Velocity object interpreting passed value as meters/sec
        /// </summary>
        /// <param name="metersPerSec">meters/sec</param>
        /// <returns></returns>
        public static Velocity FromMetersPerSec(double metersPerSec)
        {
            return new Velocity(metersPerSec);
        }

        #endregion

        public override bool Equals(object obj)
        {
            Velocity v = obj as Velocity;

            return (v == null) ? false : (this._velocity == v._velocity);
        }

        public override int GetHashCode()
        {
            return _velocity.GetHashCode();
        }

        #region binary operators

        // not implementing %, &, |, ^, <<, >>

        
        public static Velocity operator +(Velocity left, Velocity right)
        {
            if (null == left)
                throw new ArgumentNullException("left", "Cannot add a null Velocity");

            if (null == right)
                throw new ArgumentNullException("right", "Cannot add null Velocity");

            return new Velocity(left._velocity + right._velocity);
        }

        
        public static Velocity operator -(Velocity left, Velocity right)
        {
            if (null == left)
                throw new ArgumentNullException("left", "Cannot subtract a null Velocity");

            if (null == right)
                throw new ArgumentNullException("right", "Cannot subtract a null Velocity");

            return new Velocity(left._velocity - right._velocity);
        }

        
        public static Velocity operator *(Velocity velocity, double scalar)
        {
            if (null == velocity)
                throw new ArgumentNullException("velocity", "Cannot multiply a null Velocity");

            return new Velocity(velocity._velocity * scalar);
        }

        
        public static Velocity operator *(double scalar, Velocity velocity)
        {
            if (null == velocity)
                throw new ArgumentNullException("velocity", "Cannot multiply a null Velocity");

            return new Velocity(scalar * velocity._velocity);
        }

        
        public static Velocity operator /(Velocity velocity, double scalar)
        {
            if (null == velocity)
                throw new ArgumentNullException("velocity", "Cannot divide a null Velocity");

            if (0.0 == scalar)
                throw new DivideByZeroException("Cannot divide Velocity by 0");

            return new Velocity(velocity._velocity / scalar);
        }

        #endregion

        #region comparison operators

        public static bool operator ==(Velocity left, Velocity right)
        {
            bool bReturn = false;
            if (object.ReferenceEquals(left, null))
            {
                if (object.ReferenceEquals(right, null))
                {
                    //both are null, so we are ==
                    bReturn = true;
                }
            }
            else
            {
                if (!object.ReferenceEquals(left, null) &&
                    !object.ReferenceEquals(right, null))
                {
                    bReturn = left._velocity == right._velocity;
                }
            }
            return bReturn;
        }

        public static bool operator !=(Velocity left, Velocity right)
        {
            return !(left == right);
        }

        
        public static bool operator <(Velocity left, Velocity right)
        {
            if (null == left)
                throw new ArgumentNullException("left", "Cannot compare null Velocity");

            if (null == right)
                throw new ArgumentNullException("right", "Cannot compare null Velocity");

            return (left._velocity < right._velocity);
        }

        
        public static bool operator >(Velocity left, Velocity right)
        {
            if (null == left)
                throw new ArgumentNullException("left", "Cannot compare null Velocity");

            if (null == right)
                throw new ArgumentNullException("right", "Cannot compare null Velocity");

            return (left._velocity > right._velocity);
        }

        
        public static bool operator <=(Velocity left, Velocity right)
        {
            if (null == left)
                throw new ArgumentNullException("left", "Cannot compare null Velocity");

            if (null == right)
                throw new ArgumentNullException("right", "Cannot compare null Velocity");

            return (left._velocity <= right._velocity);
        }

        
        public static bool operator >=(Velocity left, Velocity right)
        {
            if (null == left)
                throw new ArgumentNullException("left", "Cannot compare null Velocity");

            if (null == right)
                throw new ArgumentNullException("right", "Cannot compare null Velocity");

            return (left._velocity >= right._velocity);
        }

        #endregion

        #region operators with other classes

        /// <summary>
        /// Implements the operator * for Length = Velocity * PrecisionTimeSpan
        /// </summary>
        /// <param name="velocity">The velocity.</param>
        /// <param name="time">The time.</param>
        /// <returns>
        /// Length
        /// </returns>
        
        public static Length operator *(Velocity velocity, PrecisionTimeSpan time)
        {
            if (null == velocity)
                throw new ArgumentNullException("velocity", "Cannot multiply a null Velocity");

            if (null == time)
                throw new ArgumentNullException("time", "Cannot multiply a null PrecisionTimeSpan");
                        
            return Length.FromMeters(velocity.MetersPerSec * time.Seconds);
        }

        /// <summary>
        /// Implements the operator * for Length = PrecisionTimeSpan * Velocity
        /// </summary>
        /// <param name="time">The time.</param>
        /// <param name="velocity">The velocity.</param>
        /// <returns>
        /// Length
        /// </returns>
        
        public static Length operator *(PrecisionTimeSpan time, Velocity velocity)
        {
            if (null == time)
                throw new ArgumentNullException("time", "Cannot divide a null PrecisionTimeSpan");

            if (null == velocity)
                throw new ArgumentNullException("velocity", "Cannot divide by a null Velocity");

            if (0.0 == velocity.MetersPerSec)
                throw new DivideByZeroException("Cannot divide Time Span by 0 Velocity");

            return Length.FromMeters(time.Seconds * velocity.MetersPerSec);
        }

        /// <summary>
        /// Implements the operator * for Acceleration = Velocity / PrecisionTimeSpan
        /// </summary>
        /// <param name="velocity">The velocity.</param>
        /// <param name="time">The time.</param>
        /// <returns>
        /// Acceleration
        /// </returns>
        
        public static Acceleration operator /(Velocity velocity, PrecisionTimeSpan time)
        {
            if (null == velocity)
                throw new ArgumentNullException("velocity", "Cannot divide a null Velocity");

            if (null == time)
                throw new ArgumentNullException("time", "Cannot divide by a null PrecisionTimeSpan");

            if (0.0 == time.Milliseconds)
                throw new DivideByZeroException("Cannot divide Velocity by 0 Time Span");

            return Acceleration.FromMetersPerSecSqrd(velocity.MetersPerSec / time.Seconds);
        }

        /// <summary>
        /// Implements the operator * for PrecisionTimeSpan = Velocity / Acceleration
        /// </summary>
        /// <param name="velocity">The velocity.</param>
        /// <param name="time">The acceleration.</param>
        /// <returns>
        /// PrecisionTimeSpan
        /// </returns>
        
        public static PrecisionTimeSpan operator /(Velocity velocity, Acceleration acceleration)
        {
            if (null == velocity)
                throw new ArgumentNullException("velocity", "Cannot divide a null Velocity");

            if (null == acceleration)
                throw new ArgumentNullException("acceleration", "Cannot divide by a null Acceleration");

            if (0.0 == acceleration.MetersPerSecSqrd)
                throw new DivideByZeroException("Cannot divide Velocity by 0 Acceleration");

            return PrecisionTimeSpan.FromSeconds(velocity.MetersPerSec / acceleration.MetersPerSecSqrd);
        }

        #endregion

        #region parsing

        public static Velocity Parse(string s)
        {
            return Common.Parse(s, _unitInfo);
        }

        public static bool TryParse(string s, out Velocity value)
        {
            try
            {
                value = Velocity.Parse(s);
                return true;
            }
            catch (Exception)
            {
                value = null;
                return false;
            }
        }

        #endregion

        /// <summary>
        /// Returns a string appended with default units (e.g. "1.23 m/sec^2").
        /// </summary>
        /// <returns>
        /// A string that represents this instance
        /// </returns>
        public override string ToString()
        {
            return ToString(DefaultUnits);
        }

        /// <summary>
        /// overload that returns a string appended with specified units (e.g. "1.23 ft/sec^2").
        /// </summary>
        /// <param name="units"></param>
        /// <returns></returns>
        public string ToString(Unit units)
        {
            double value = (double)_unitInfo[units].PropertyGetter.Invoke(this, null);

            return $"{value} {_unitInfo[units].Abbreviation[0]}";
        }
    }
}
