using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Web.Routing;
using System.Web.Security;
using System.Configuration;
using System.IO;
using System.Web.Script.Serialization;

using BLL.Services.System;
using Model.Entities.Users;

namespace Web.Controllers.Base
{
    public abstract class BaseApiController : BaseController
    {
        protected User CurrentUser { private set; get; }
        protected readonly PermissionServices permissionServices;
        protected readonly TokenServices TokenServices = new TokenServices();

        /// <summary>
        /// Http Post Json request
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        protected T GetJson<T>()
        {
            using (var stream = HttpContext.Request.InputStream)
            {
                using (StreamReader rd = new StreamReader(stream))
                {
                    return new JavaScriptSerializer().
                        Deserialize<T>(rd.ReadToEnd());
                }
            }
        }


        protected BaseApiController()
        {
            permissionServices = new PermissionServices(UOW);
        }

        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);

            var cookie = HttpContext.Request.Cookies;

            if (cookie.AllKeys.Contains("AuthToken"))
            {
                var auth = cookie.Get("AuthToken");

                if (auth.Value.Count() != 0)
                {
                    TokenData data = null;

                    try
                    {
                        data = TokenServices.GetData(auth.Value);
                    }
                    catch { return; }

                    if (!data.IsValid)
                        return;

                    CurrentUser = UOW.Repo_User.All.
                        FirstOrDefault(e => e.ID == data.ID);
                }

            }

        }
    }
}