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. FromRadiansPerSec).
    /// 
    /// Properties (e.g. RadiansPerSec) 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. 
    /// Angle, AngularAcceleration).
    /// </summary>
    [Serializable]
    [DataContract]
    public class AngularVelocity
    {
        public enum Unit
        {
            DegreesPerSec,
            RadiansPerSec,
            MilliradiansPerSec
        }

        public static IDictionary<Unit, List<string>> UnitAbbreviations = new Dictionary<Unit, List<string>>()
        {
            {Unit.DegreesPerSec,      new List<string>(){ "deg/sec" } },
            {Unit.RadiansPerSec,      new List<string>(){ "rad/sec" } },
            {Unit.MilliradiansPerSec, new List<string>(){ "mrad/sec" } },
        };

        private const Unit DefaultUnits = Unit.RadiansPerSec;
        private const double DegreesPerRadian = 180 / Math.PI;

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

        // map: unit => abbreviation, conversion method and property
        private static IDictionary<Unit, UnitInfo<AngularVelocity>> _unitInfo = new Dictionary<Unit, UnitInfo<AngularVelocity>>()
        {
            { Unit.DegreesPerSec,      new UnitInfo<AngularVelocity>(UnitAbbreviations[Unit.DegreesPerSec],      FromDegreesPerSec,      typeof(AngularVelocity).GetProperty("DegreesPerSec").GetGetMethod()) },
            { Unit.MilliradiansPerSec, new UnitInfo<AngularVelocity>(UnitAbbreviations[Unit.MilliradiansPerSec], FromMilliradiansPerSec, typeof(AngularVelocity).GetProperty("MilliradiansPerSec").GetGetMethod()) },
            { Unit.RadiansPerSec,      new UnitInfo<AngularVelocity>(UnitAbbreviations[Unit.RadiansPerSec],      FromRadiansPerSec,      typeof(AngularVelocity).GetProperty("RadiansPerSec").GetGetMethod()) }
        };

        /// <summary>
        /// Prevents a default instance of the <see cref="AngularVelocity"/> 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 AngularVelocity()
        {
            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 - radians/sec.</param>
        private AngularVelocity(double velocity)
        {
            _velocity = velocity;
        }

        #region conversion properties

        /// <summary>
        /// Returns degrees/sec as type double
        /// </summary>
        /// <value>
        /// degrees/sec
        /// </value>
        public double DegreesPerSec
        {
            get { return _velocity * DegreesPerRadian; }
        }

        /// <summary>
        /// Returns degrees/sec as type double
        /// </summary>
        /// <value>
        /// degrees/sec
        /// </value>
        public double MilliradiansPerSec
        {
            get { return _velocity * 1000; }
        }

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

        #endregion

        #region creation methods

        /// <summary>
        /// Returns AngularVelocity object interpreting passed value as degrees/sec
        /// </summary>
        /// <param name="degreesPerSec">degrees/sec</param>
        /// <returns></returns>
        public static AngularVelocity FromDegreesPerSec(double degreesPerSec)
        {
            return new AngularVelocity(degreesPerSec / DegreesPerRadian);
        }

        /// <summary>
        /// Returns AngularVelocity object interpreting passed value as milliradians/sec
        /// </summary>
        /// <param name="milliradiansPerSec">milliradians/sec</param>
        /// <returns></returns>
        public static AngularVelocity FromMilliradiansPerSec(double milliradiansPerSec)
        {
            return new AngularVelocity(milliradiansPerSec / 1000);
        }

        /// <summary>
        /// Returns AngularVelocity object interpreting passed value as radians/sec
        /// </summary>
        /// <param name="radiansPerSec">radians/sec</param>
        /// <returns></returns>
        public static AngularVelocity FromRadiansPerSec(double radiansPerSec)
        {
            return new AngularVelocity(radiansPerSec);
        }

        #endregion

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

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

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

        #region binary operators

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        #endregion

        #region comparison operators

        public static bool operator ==(AngularVelocity left, AngularVelocity 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 !=(AngularVelocity left, AngularVelocity right)
        {
            return !(left == right);
        }

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

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

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

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

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

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

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

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

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

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

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

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

        #endregion

        #region operators with other classes

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

            if (null == time)
                throw new ArgumentNullException("time", "Cannot multiply with null PrecisionTimeSpan");
            
            return Angle.FromRadians(velocity.RadiansPerSec * time.Seconds);
        }

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

            if (null == time)
                throw new ArgumentNullException("time", "Cannot multiply with null PrecisionTimeSpan");
            
            return Angle.FromRadians(time.Seconds * velocity.RadiansPerSec);
        }

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

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

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

            return AngularAcceleration.FromRadiansPerSecSqrd(velocity.RadiansPerSec / time.Seconds);
        }

        /// <summary>
        /// Implements the operator / for PrecisionTimeSpan = AngularVelocity / AngularAcceleration
        /// </summary>
        /// <param name="velocity">The velocity.</param>
        /// <param name="acceleration">The acceleration.</param>
        /// <returns>
        /// Angle
        /// </returns>
        
        public static PrecisionTimeSpan operator /(AngularVelocity velocity, AngularAcceleration acceleration)
        {
            if (null == velocity)
                throw new ArgumentNullException("velocity", "Cannot divide with null AngularVelocity");

            if (null == acceleration)
                throw new ArgumentNullException("acceleration", "Cannot divide with null AngularAcceleration");

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

            return PrecisionTimeSpan.FromSeconds(velocity.RadiansPerSec / acceleration.RadiansPerSecSqrd);
        }

        #endregion

        #region parsing

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

        public static bool TryParse(string s, out AngularVelocity value)
        {
            try
            {
                value = AngularVelocity.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]}";
        }
    }
}
