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

namespace Raytheon.Units
{
    /// <summary>
    /// This class represents electrical resistance.  
    /// 
    /// 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. FromOhms).
    /// 
    /// Properties (e.g. KiloOhms) 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, Voltage).
    /// </summary>
    [Serializable]
    [DataContract]
    public class Resistance
    {
        public enum Unit
        {
            Ohms,
            KiloOhms,
            MegaOhms
        }

        public static IDictionary<Unit, List<string>> UnitAbbreviations = new Dictionary<Unit, List<string>>()
        {
            {Unit.Ohms,      new List<string>(){ "Ohm" } },
            {Unit.KiloOhms,  new List<string>(){ "kOhm" } },
            {Unit.MegaOhms,  new List<string>(){ "MOhm" } },
        };

        private const Unit DefaultUnits = Unit.Ohms;
        private const int KiloOhmsPerOhm = 1000;
        private const int MegaOhmsPerOhm = 1000000;

        [DataMember(Name = "Resistance", IsRequired = true)]
        private double _resistance; // ohms

        // map: unit => abbreviation, conversion method and property
        private static IDictionary<Unit, UnitInfo<Resistance>> _unitInfo = new Dictionary<Unit, UnitInfo<Resistance>>()
        {
            { Unit.Ohms,     new UnitInfo<Resistance>(UnitAbbreviations[Unit.Ohms],     FromOhms,     typeof(Resistance).GetProperty("Ohms").GetGetMethod()) },
            { Unit.KiloOhms, new UnitInfo<Resistance>(UnitAbbreviations[Unit.KiloOhms], FromKiloOhms, typeof(Resistance).GetProperty("KiloOhms").GetGetMethod()) },
            { Unit.MegaOhms, new UnitInfo<Resistance>(UnitAbbreviations[Unit.MegaOhms], FromMegaOhms, typeof(Resistance).GetProperty("MegaOhms").GetGetMethod()) }
        };

        /// <summary>
        /// Prevents a default instance of the <see cref="Resistance"/> 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 Resistance()
        {
            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="resistance">The resistance - ohms</param>
        private Resistance(double resistance)
        {
            _resistance = resistance;
        }

        #region conversion properties

        /// <summary>
        /// Returns ohms as type double
        /// </summary>
        /// <value>
        /// ohms
        /// </value>
        public double Ohms
        {
            get { return _resistance; }
        }

        /// <summary>
        /// Returns kiloohms as type double
        /// </summary>
        /// <value>
        /// kiloohms
        /// </value>
        public double KiloOhms
        {
            get { return _resistance / KiloOhmsPerOhm; }
        }

        /// <summary>
        /// Returns megaohms as type double
        /// </summary>
        /// <value>
        /// megaohms
        /// </value>
        public double MegaOhms
        {
            get { return _resistance / MegaOhmsPerOhm; }
        }

        #endregion

        #region creation methods

        /// <summary>
        /// Returns Resistance object interpreting passed value as kiloohms
        /// </summary>
        /// <param name="kiloohms">kiloohms</param>
        /// <returns></returns>
        public static Resistance FromKiloOhms(double kiloOhms)
        {
            return new Resistance(kiloOhms * KiloOhmsPerOhm);
        }

        /// <summary>
        /// Returns Resistance object interpreting passed value as megaohms
        /// </summary>
        /// <param name="megaohms">megaohms</param>
        /// <returns></returns>
        public static Resistance FromMegaOhms(double megaOhms)
        {
            return new Resistance(megaOhms * MegaOhmsPerOhm);
        }

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

        #endregion

        public override bool Equals(object obj)
        {
            Resistance r = obj as Resistance;

            return (r == null) ? false : (this._resistance == r._resistance);
        }

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

        #region binary operators

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

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

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

            return new Resistance(left._resistance + right._resistance);
        }

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

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

            return new Resistance(left._resistance - right._resistance);
        }

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

            return new Resistance(resistance._resistance * scalar);
        }

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

            return new Resistance(scalar * resistance._resistance);
        }

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

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

            return new Resistance(resistance._resistance / scalar);
        }

        #endregion

        #region comparison operators

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        #endregion

        #region operators with non-resistance classes

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

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

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

            return Voltage.FromVolts(resistance.Ohms * current.Amps);
        }

        #endregion

        #region parsing

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

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