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 voltage.  
    /// 
    /// 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. FromVolts).
    /// 
    /// Properties (e.g. Volts) 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. 
    /// Current, Resistance).
    /// </summary>
    [Serializable]
    [DataContract]
    public class Voltage
    {
        public enum Unit
        {
            Volts,
            Millivolts
        }

        public static IDictionary<Unit, List<string>> UnitAbbreviations = new Dictionary<Unit, List<string>>()
        {
            {Unit.Volts,      new List<string>(){ "V" } },
            {Unit.Millivolts, new List<string>(){ "mV" } },
        };

        private const Unit DefaultUnits = Unit.Volts;

        [DataMember(Name = "Voltage", IsRequired = true)]
        private double _voltage; // volts

        // map: unit => abbreviation, conversion method and property
        private static IDictionary<Unit, UnitInfo<Voltage>> _unitInfo = new Dictionary<Unit, UnitInfo<Voltage>>()
        {
            { Unit.Volts,      new UnitInfo<Voltage>(UnitAbbreviations[Unit.Volts],      FromVolts,      typeof(Voltage).GetProperty("Volts").GetGetMethod()) },
            { Unit.Millivolts, new UnitInfo<Voltage>(UnitAbbreviations[Unit.Millivolts], FromMillivolts, typeof(Voltage).GetProperty("Millivolts").GetGetMethod()) }
        };

        /// <summary>
        /// Prevents a default instance of the <see cref="Voltage"/> 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 Voltage()
        {
            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="voltage">The voltage - volts.</param>
        private Voltage(double voltage)
        {
            _voltage = voltage;
        }

        #region conversion properties

        public double Volts
        {
            get { return _voltage; }
        }

        
        public double Millivolts
        {
            get { return _voltage * 1000; }
        }

        #endregion

        #region creation methods

        /// <summary>
        /// Returns Voltage object interpreting passed value as volts
        /// </summary>
        /// <param name="volts">volts</param>
        /// <returns></returns>
        public static Voltage FromVolts(double volts)
        {
            return new Voltage(volts);
        }

        /// <summary>
        /// Returns Voltage object interpreting passed value as millivolts
        /// </summary>
        /// <param name="millivolts">millivolts</param>
        /// <returns></returns>
        
        
        public static Voltage FromMillivolts(double millivolts)
        {
            return new Voltage(millivolts / 1000);
        }

        #endregion

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

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

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

        #region binary operators

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

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

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

            return new Voltage(left._voltage + right._voltage);
        }

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

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

            return new Voltage(left._voltage - right._voltage);
        }

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

            return new Voltage(voltage._voltage * scalar);
        }

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

            return new Voltage(scalar * voltage._voltage);
        }

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

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

            return new Voltage(voltage._voltage / scalar);
        }

        #endregion

        #region comparison operators

        public static bool operator ==(Voltage left, Voltage 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._voltage == right._voltage;
                }
            }
            return bReturn;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

        #endregion

        #region operators with non-Voltage classes

        /// <summary>
        /// Implements the operator * for Current = Voltage / Resistance
        /// </summary>
        /// <param name="voltage">The voltage.</param>
        /// <param name="time">The resistance.</param>
        /// <returns>
        /// Current
        /// </returns>
        
        public static Current operator /(Voltage voltage, Resistance resistance)
        {
            if (null == voltage)
                throw new ArgumentNullException("voltage", "Cannot divide a null Voltage");

            if (null == resistance)
                throw new ArgumentNullException("resistance", "Cannot divide by a null Resistance");

            if (0.0 == resistance.Ohms)
                throw new DivideByZeroException("Cannot divide Voltage by 0 Resistance");

            return Current.FromAmps(voltage.Volts / resistance.Ohms);
        }

        /// <summary>
        /// Implements the operator * for Resistance = Voltage / Current
        /// </summary>
        /// <param name="voltage">The voltage.</param>
        /// <param name="time">The current.</param>
        /// <returns>
        /// Resistance
        /// </returns>
        
        public static Resistance operator /(Voltage voltage, Current current)
        {
            if (null == voltage)
                throw new ArgumentNullException("voltage", "Cannot divide a null Voltage");

            if (null == current)
                throw new ArgumentNullException("current", "Cannot divide by a null Current");

            if (0.0 == current.Amps)
                throw new DivideByZeroException("Cannot divide Voltage by 0 Current");

            return Resistance.FromOhms(voltage.Volts / current.Amps);
        }

        #endregion

        #region parsing

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

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