using DataAccessLayer.Entities;
using DataAccessLayer.Filtering;
using DataAccessLayer.Units;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace WcfServices.Authorization
{
    public class RoleAuthorizationManager : ServiceAuthorizationManager
    {
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            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 = operationContext.ServiceSecurityContext.PrimaryIdentity.Name
                         }
                    }
                };
                #endregion buildFilter
                var user = userUnit.GetAsync(filter).Result.FirstOrDefault();
                if (user == null)
                    throw new FaultException($"User {operationContext.ServiceSecurityContext.PrimaryIdentity.Name} not found.");

                var roleNames = user.Roles.Select(x => x.Identificator).ToArray();
                operationContext.ServiceSecurityContext.AuthorizationContext.Properties
                     ["Principal"] = new GenericPrincipal
                     (operationContext.ServiceSecurityContext.PrimaryIdentity, roleNames);

                return true;
            }
        }
    }
}
