using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LHDN.CRM.BC.Repositories;
using LHDN.CRM.BC.Common;
namespace LHDN.CRM.Web.Filters
{
    public class CRMAuthorizeAttribute : AuthorizeAttribute
    {
        public CRMAuthorizeAttribute(params string[] roles) : base()
        {
            Roles = string.Join(",", roles);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            bool blnUserInRole = false;

            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                string strAccountName = filterContext.HttpContext.User.Identity.Name;

                foreach (var role in Roles.Split(","))
                {
                    if (System.Web.Security.Roles.Provider.IsUserInRole(strAccountName, role))
                    {
                        blnUserInRole = true;
                    }
                }

                if (!blnUserInRole)
                {
                    filterContext.HttpContext.Response.StatusCode = 403;
                    //LogWriter.LogMessage("User not authorized : " + strAccountName);
                    if (!filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        filterContext.HttpContext.Response.RedirectToRoute("Default", new
                        {
                            controller = "Error",
                            action = "AccessDenied"
                        });
                    }

                    filterContext.HttpContext.Response.End();
                }
            }
            //else
            //{
            //    Helper.LogMessage("User not authenticated");
            //}

            if (!blnUserInRole)
            {
                //Helper.LogMessage("User dont have roles");
                base.HandleUnauthorizedRequest(filterContext);
            }

        }
    }
}