using System;
using System.Collections.Generic;
using System.Text;

namespace ImageResizer.Resizing {
    public enum UnitType {
        Pixels,
        Percentages
    }
    public struct UnitR {

        public UnitR(double value, UnitType units) {
            this._value = value;
            this._units = units;
        }
        public UnitR(string str) {
            UnitR parsed;
            if (!UnitR.TryParse(str, out parsed)) throw new ArgumentException("Failed to parse '" + str + "'.");
            this._value = parsed.Value;
            this._units = parsed.Units;
        }

        protected double _value = 0;

        public double Value {
            get { return _value; }
        }
        protected UnitType _units = UnitType.Pixels;

        public UnitType Units {
            get { return _units; }
        }

        public override string ToString() {
            return Value.ToString() + (Units == UnitType.Pixels ? "px" : "pc");
        }

        public override bool Equals(object obj) {
            if (obj == null || !(obj is UnitR)) {
                return false;
            }
            UnitR unit = (UnitR)obj;
            return unit.Units == this.Units && unit._value == this._value;
        }


        public static readonly UnitR Empty = default(UnitR);
  

        private static readonly string[] pixelNames = new string[] { "px", "pixels" };
        private static readonly string[] percentagesNames = new string[] { "pc","pct","percent"};

        public static bool TryParse(string s, out UnitR result, UnitType defaultUnit = UnitType.Pixels){
            result = Empty;
            //Trim whitespace, fail if empty
            if (s != null) s = s.Trim();
            if (string.IsNullOrEmpty(s)) return false;

            UnitType type = defaultUnit;

            //Find which suffix is being used
            string suffix = null;
            foreach (string name in pixelNames) 
                if (s.EndsWith(name, StringComparison.OrdinalIgnoreCase)) 
                { type = UnitType.Pixels; suffix = name; break; }

            if (suffix == null)
                foreach (string name in percentagesNames) 
                    if (s.EndsWith(name, StringComparison.OrdinalIgnoreCase)) 
                    { type = UnitType.Percentages;suffix = name; break; }

            //Strip 'suffix' off
            if (suffix != null) s = s.Substring(0, s.Length - suffix.Length).Trim();

            //Parse double
            double value = 0;
            if (!double.TryParse(s, out value)) return false;

            result = new UnitR(value, type);
            return true;
        }

    }
}
