using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Kreta.Framework;
using Kreta.Web.Controllers.Logic;

namespace Kreta.Web.Security
{
    public class ApiSessionAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //TODO ezt itt ki kellene szedni, ellenorzo keszitesekor
            if (actionContext.ControllerContext.ControllerDescriptor.ControllerName == "Mobile")
            {
                return;
            }
            if (SkipAuthorization(actionContext))
            {
                return;
            }
            if (IsAuthorized(actionContext))
            {
                SessionHandler.UpdateSessionTime();
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            string sessionId = ClaimData.SessionId;
            if (sessionId != null)
            {
                return SDAServer.Instance.SessionManager.IsSessionAlive(sessionId);
            }

            return false;
        }

        private static bool SkipAuthorization(HttpActionContext actionContext)
        {
            return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0
                   || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0;
        }
    }
}