using DataAccessLayer.Entities;
using DataAccessLayer.Filtering;
using DataAccessLayer.Units;
using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using WcfServices.Authorization;

namespace WcfServices.Authorization
{
    public class IdentityValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {

            using (var userUnit = new UnitOfWork<User>(new DataAccessLayer.ISDbContext()))
            {
                #region buildFilter
                var filter = new Filter()
                {
                    Conditions = new List<ConditionItem>()
                    {
                         new ConditionItem()
                         {
                              Column = nameof(User.Login),
                              Type = ConditionTypeEnum.Equal,
                              Value = userName
                         }
                    }
                };
                #endregion buildFilter
                var user = userUnit.GetAsync(filter).Result.FirstOrDefault();

                if (user == null)
                    throw new FaultException($"User {userName} not found.");

                if (!PasswordHelper.ValidatePassword(user.PasswordHash, password))
                    throw new FaultException("Wrong password");
                
            }


        }
    }
}
