﻿using System;
using System.Reflection;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace Com.Piwigo.Lib.DTO.Helper
{
    public static class PwgEnumHelper<T>
    {
        static PwgEnumHelper()
        {
            if (!typeof(T).IsEnum) {
                throw new ArgumentException(String.Format("PwgEnumHelper<T>(): The type {0} is not a enum.", typeof(T).Name));
            }
        }

        internal static String StringValueOf(T value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            XmlEnumAttribute[] attributes = (XmlEnumAttribute[])fi.GetCustomAttributes(typeof(XmlEnumAttribute), false);
            if (attributes.Length > 0)
            {
                return attributes[0].Name;
            }
            else
            {
                return value.ToString();
            }
        }

        internal static T enumValueOf(String value) 
        {
            Type enumType = typeof(T);
            Array values = Enum.GetValues(enumType);
            foreach (T enumValue in values)
            {
                if (StringValueOf(enumValue).Equals(value))
                {
                    return enumValue;
                }
            }

            throw new ArgumentException(String.Format("PwgEnumHelper<{0}>.enumValueOf({1}): The String is not a description or value of the specified enum.", typeof(T).Name, value));
        }

        public static List<KeyValuePair<T, String>> buildChoiceList()
        {
            List<KeyValuePair<T, String>> lst = new List<KeyValuePair<T, String>>();

            foreach (T item in Enum.GetValues(typeof(T)))
	        {
                lst.Add(new KeyValuePair<T, String>(item, StringValueOf(item)));
	        }
  
            return lst;
        }
    }
}
