using System;
using System.Linq;
using InABox.Clients;

namespace InABox.Core
{
    public static class SecurityDescriptorUtils
    {
        public static bool IsSupported(Type type)
        {
            var entities = type.GetInheritedGenericTypeArguments().ToArray();
            if (entities.Length > 1)
                return ClientFactory.IsSupported(entities.Skip(1).ToArray());
            return true;
        }

        public static string Type(Type type)
        {
            type = type.BaseType?.GetGenericArguments().FirstOrDefault();
            if (type != null)
            {
                var caption = type.GetCustomAttributes(typeof(Caption), true).FirstOrDefault() as Caption;
                return caption != null ? caption.Text : type.EntityName();
            }

            return "General";
        }

        public static string Code(Type type)
        {
            return type.EntityName().Split('.').Last();
        }

        public static string Description(Type type)
        {
            var caption = type.GetCustomAttributes(typeof(Caption), true).FirstOrDefault() as Caption;
            return caption != null ? caption.Text : type.EntityName();
        }
    }
}