using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Logging;
using ServiceStack.Web;
using System;
namespace MediaBrowser.Controller.Net
{
    public class LoggedAttribute : Attribute, IHasRequestFilter
    {
        public ILogger Logger { get; set; }
        public IUserManager UserManager { get; set; }
        public ISessionManager SessionManager { get; set; }
        public IAuthorizationContext AuthorizationContext { get; set; }
        /// 
        /// The request filter is executed before the service.
        /// 
        /// The http request wrapper
        /// The http response wrapper
        /// The request DTO
        public void RequestFilter(IRequest request, IResponse response, object requestDto)
        {
            //This code is executed before the service
            var auth = AuthorizationContext.GetAuthorizationInfo(request);
            if (auth != null)
            {
                User user = null;
                if (!string.IsNullOrWhiteSpace(auth.UserId))
                {
                    var userId = auth.UserId;
                    user = UserManager.GetUserById(userId);
                }
                string deviceId = auth.DeviceId;
                string device = auth.Device;
                string client = auth.Client;
                string version = auth.Version;
                if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device) && !string.IsNullOrEmpty(version))
                {
                    var remoteEndPoint = request.RemoteIp;
                    SessionManager.LogSessionActivity(client, version, deviceId, device, remoteEndPoint, user);
                }
            }
        }
        /// 
        /// A new shallow copy of this filter is used on every request.
        /// 
        /// IHasRequestFilter.
        public IHasRequestFilter Copy()
        {
            return this;
        }
        /// 
        /// Order in which Request Filters are executed.
        /// <0 Executed before global request filters
        /// >0 Executed after global request filters
        /// 
        /// The priority.
        public int Priority
        {
            get { return 0; }
        }
    }
}