using System;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Redis;

namespace Siger.ApiCommon
{
    [Route("api/[controller]/[action]")]
    [EnableCors("Cors")]
    //[TokenValidateFilter]
    public class AuthController : ControllerBase
    {
        public const int PageIndex = 1;

        /// <summary>
        /// default pagesize is 10
        /// </summary>
        public const int PageSize = 10;

        public int CompanyId => TokenValue == null ? 0 : TokenValue.CompanyId;
        /// <summary>
        /// project id
        /// </summary>
        public int ProjectId => TokenValue == null ? 0 : TokenValue.ProjectId;

        /// <summary>
        /// user id
        /// </summary>
        public int UserId => TokenValue == null ? 0 : TokenValue.UserId;

        /// <summary>
        /// user role id
        /// </summary>
        public int RoleId => TokenValue == null ? 0 : TokenValue.RoleId;

        /// <summary>
        /// token value
        /// </summary>
        public TokenValue TokenValue
        {
            get
            {
                var hasValue = HttpContext.Request.Headers.TryGetValue(ParameterConstant.Token, out StringValues token);
                if (hasValue)
                {
                   return RedisCache.Instance.GetTokenValue(token);
                }
                var hasParameter = HttpContext.Request.Headers.TryGetValue(ParameterConstant.Referer, out StringValues referer);
                if (hasParameter && referer.ToStr().Contains("projectid="))
                {
                    return CreateToken(referer.ToStr());
                }
                return null;
            }
        }

        private TokenValue CreateToken(string referer)
        {
            var companyid = TokenHelper.GetQueryString("companyid", referer).ToInt();
            var projectid = TokenHelper.GetQueryString("projectid", referer).ToInt();
            var userid = TokenHelper.GetQueryString("userid", referer).ToInt();

            return new TokenValue(companyid == 0 ? projectid : companyid, projectid, userid, 0);
        }

        public string ServerIpAddress
        {
            get
            {
                try
                {
                    return Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
                }
                catch
                {
                    return "127.0.0.1";
                }
            }
        }
    }
}