using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authorization;
using GreenTree.Strohrmann.ERP.Domain.Model;
using System.Security.Claims;

namespace GreenTree.Strohrmann.ERP.Services.Authorization
{
    public class CookieAuthorizationService : IAuthorizationService
    {
        #region Implementation

        /// <summary>
        /// Check wether the user has a specific policy
        /// </summary>
        /// <param name="identity">The user identity.</param>
        /// <param name="policy">The policy to be checked.</param>
        public bool UserHasPolicy(IIdentity identity, string policy)
        {
            var claimsIdentity = identity as ClaimsIdentity;

            if (claimsIdentity == null) return false;

            return claimsIdentity.Claims
                .Any(c => c.Type == "Policy" && c.Value == policy);
        }

        /// <summary>
        /// Check wether the user has any policy regarding base data management
        /// </summary>
        /// <param name="identity">The user identity.</param>
        public bool UserHasBasedataPolicy(IIdentity identity)
        {
            var claimsIdentity = identity as ClaimsIdentity;

            if (claimsIdentity == null) return false;

            return claimsIdentity.Claims
                .Any(c => c.Type == "Policy" &&
                         (c.Value.StartsWith("Customer") ||
                          c.Value.StartsWith("Employee") ||
                          c.Value.StartsWith("Material") ||
                          c.Value.StartsWith("Supplier")));
        }

        /// <summary>
        /// Check wether the user has any policy in a specific category
        /// </summary>
        /// <param name="identity">The user identity.</param>
        /// <param name="category">The category (e.g. 'Customer').</param>
        public bool UserHasCategoryPolicy(IIdentity identity, string category)
        {
            var claimsIdentity = identity as ClaimsIdentity;

            if (claimsIdentity == null) return false;

            return claimsIdentity.Claims
                .Any(c => c.Type == "Policy" && c.Value.StartsWith(category));
        }

        #endregion
    }
}
