using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using GreenTree.Nachtragsmanagement.Core.Domain.User;
using FluentValidation.Attributes;
using GreenTree.Nachtragsmanagement.Web.Validation.Admin.User;

namespace GreenTree.Nachtragsmanagement.Web.Models.Admin.User
{
    public class UserDataModel
    {
        public int Id { get; set; }
        public string CustomNumber { get; set; }
        public string Forename { get; set; }
        public string Lastname { get; set; }
        public string MailAddress { get; set; }
        public string Password { get; set; }
        public ICollection<int> RoleValues { get; set; }
        public ICollection<string> RoleDescriptions { get; set; }
        public string RoleDescription
        {
            get
            {
                if (RoleDescriptions == null)
                    return String.Empty;
                else
                    return String.Join(", ", RoleDescriptions);
            }
        }

        public UserDataModel()
        {
            RoleValues = new List<int>();
            RoleDescriptions = new List<string>();
        }

        public static UserDataModel FromUser(Core.Domain.User.User userEntity, bool newWhenIsNull)
        {
            if (userEntity == null && newWhenIsNull)
                return new UserDataModel
                {
                    Id = -1
                };

            if (userEntity == null && !newWhenIsNull)
                throw new ArgumentNullException("userEntity", "Cannot create UserDataModel from NULL user entity.");

            return new UserDataModel
            {
                Id = userEntity.Id,
                CustomNumber = userEntity.CustomNumber,
                Forename = userEntity.Forename,
                Lastname = userEntity.Lastname,
                MailAddress = userEntity.MailAddress,
                RoleValues = 
                    userEntity.Roles
                        .Select(r => r.Id)
                        .ToList(),
                RoleDescriptions =
                    userEntity.Roles
                        .Select(r => r.Description)
                        .ToList()
            };
        }

        public Core.Domain.User.User ToUser()
        {
            return new Core.Domain.User.User
            {
                Id = this.Id,
                CustomNumber = this.CustomNumber,
                Forename = this.Forename,
                Lastname = this.Lastname,
                MailAddress = this.MailAddress
            };
        }
    }
}