using System;
using System.IO;
using System.Threading.Tasks;
using Datory;
using GxPress.Common.AppOptions;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.Service.Interface;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

namespace GxPress.Service.Implement
{
    public class ApiLogService : IApiLogService
    {
        private readonly IConfiguration _configuration;

        private readonly Repository<UserLogin> _repository;
        private readonly Repository<User> _userRepository;

        public ApiLogService(IConfiguration configuration, IOptionsMonitor<DatabaseOptions> dbOptionsAccessor)
        {
            _configuration = configuration;
            var databaseType =
           StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            //_connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<UserLogin>(database);
            _userRepository = new Repository<User>(database);
        }

        public async Task DataSave(HttpContext context, long responseTime, int userId)
        {
            var isLog = _configuration.GetValue<bool>("ApiLog:IsEnable");
            // if (isLog)
            // {
            var requestMethod = context.Request.Method;
            var requestURL = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}";
            //var accessToken = context.GetTokenAsync("access_token").Result;//添加身份验证的项目可以使用此方法获取到access_toekn
            var accessToken = string.Empty;
            var requestBody = string.Empty;
            if (requestMethod == "POST")
            {
                context.Request.Body.Seek(0, SeekOrigin.Begin);
                var _reader = new StreamReader(context.Request.Body);
                requestBody = _reader.ReadToEnd();
            }
            var model = new UserLogin
            {
                AccessToken = accessToken,
                AccessTime = DateTime.Now,
                AccessAction = requestMethod,
                AccessApiUrl = requestURL,
                QueryString = context.Request.QueryString.ToString(),
                Body = requestBody,
                HttpStatus = context.Response.StatusCode,
                ClientIP = context.Connection.RemoteIpAddress.ToString(),
                ResponseTime = responseTime,
                UserId = userId
            };
            await _repository.InsertAsync(model);
            //
            await _userRepository.UpdateAsync(Q.Where(nameof(User.Id), userId).Set(nameof(User.LoginTime), DateTime.Now));
            //}
        }
    }
}