using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GreenTree.Nachtragsmanagement.Web.Models.Admin.User
{
    public class RoleDataModel
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public int Level { get; set; }
        public bool SeeOnlyAssigned { get; set; }
        public ICollection<int> FunctionValues { get; set; }
        public ICollection<string> FunctionDescriptions { get; set; }
        public string FunctionDescription
        {
            get
            {
                if (FunctionDescriptions == null)
                    return String.Empty;
                else
                    return String.Join(", ", FunctionDescriptions);
            }
        }
        public string UserDescription { get; set; }

        public RoleDataModel()
        {
            FunctionValues = new List<int>();
            FunctionDescriptions = new List<string>();
        }

        public static RoleDataModel FromRole(Core.Domain.User.Role roleEntity, bool newWhenIsNull)
        {
            if (roleEntity == null && newWhenIsNull)
                return new RoleDataModel
                {
                    Id = -1
                };

            if (roleEntity == null && !newWhenIsNull)
                throw new ArgumentNullException("roleEntity", "Cannot create RoleDataModel from NULL role entity.");

            return new RoleDataModel
            {
                Id = roleEntity.Id,
                Description = roleEntity.Description,
                Level = roleEntity.Level,
                SeeOnlyAssigned = roleEntity.SeeOnlyAssigned,
                FunctionValues =
                    roleEntity.Functions
                        .Select(r => r.Id)
                        .ToList(),
                FunctionDescriptions =
                    roleEntity.Functions
                        .Select(r => r.Description)
                        .ToList(),
                UserDescription =
                    String.Join(", ", 
                        roleEntity.Users
                            .Select(u => u.Lastname))
            };
        }

        public Core.Domain.User.Role ToRole()
        {
            return new Core.Domain.User.Role
            {
                Id = this.Id,
                Description  = this.Description,
                Level = this.Level
            };
        }
    }
}