using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Model.Entities.Base;
using Model.UnitsOfWork;

namespace Model.Entities.Users
{
    public class Repo_User : BaseRepository<User>
    {
        public override void RepoInit()
        {
            if (All_NoTrack.Count() == 0)
            {
                Create(new User()
                {
                    Login = "Admin",
                    Password = "Admin",
                    IsActive = true,
                    Groups = new List<Group>()
                    {
                        UOW.Repo_Group.GetDefaultGroup(EnumDefaultGroups.Администраторы)
                    }
                });
            }
        }
        public Repo_User(UOW UOW) : base(UOW) { }

        protected override void Validation_Create(User elem)
        {
            if (string.IsNullOrEmpty(elem.Login) || string.IsNullOrEmpty(elem.Password))
                throw new Exception("Login or Password is null or empty");

            if (All_NoTrack.FirstOrDefault(e => e.Login == elem.Login) != null)
                throw new Exception("login already exists");

            if (elem.Groups.Count() == 0)
                throw new Exception("user groups is empty");
        }

        protected override void Validation_Update(User old, User elem)
        {
            if (string.IsNullOrEmpty(elem.Login) || string.IsNullOrEmpty(elem.Password))
                throw new Exception("Login or Password is null or empty");

            if (old.Login != elem.Login)
                if (All_NoTrack.FirstOrDefault(e => e.Login == elem.Login) != null)
                    throw new Exception("Change login already exists");

            if (elem.Groups.Count() == 0)
                throw new Exception("user groups is empty");            
        }

        protected override void Validation_Delete(User elem)
        {
            if (elem.ID == 1)
                throw new Exception("Error try admin delete");
        }
    }
}
