using Hotline.Settings;
using Hotline.Tools;
using MapsterMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using System.Text;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.Systems
{
	public class SystemLogApplication: ISystemLogApplication, IScopeDependency
	{
		private readonly IMapper _mapper;
		private readonly IRepository<SystemLog> _systemLogRepository;
		public SystemLogApplication(IMapper mapper, IRepository<SystemLog> systemLogRepository) { _mapper = mapper; _systemLogRepository = systemLogRepository; }

		public async Task AddLog<T>(string name, string res, T entity, HttpContext context, string crName ="") {
			SystemLog log = new SystemLog();
			log.Name = name;
			var Method = "";
			switch (context.Request.Method.ToUpper())
			{
				case "GET":
					Method = "GET";
					log.ExecuteParam = context.Request.QueryString.Value;
					break;

				case "POST":
					Method = "POST";
					log.ExecuteUrl += context.Request.QueryString.Value;
					log.ExecuteParam = JsonConvert.SerializeObject(entity);
					break;
			}
			log.ExecuteUrl = Method + "|" + context.Request.Path;
			log.Status = 1;
			log.ExecuteResult = JsonConvert.SerializeObject(res);
			log.IpUrl = context.Connection.RemoteIpAddress.ToString();
			log.InitId();
			await  _systemLogRepository.AddAsync(log);
			if (!string.IsNullOrEmpty(crName))
				await _systemLogRepository.Updateable().SetColumns(l => new SystemLog() { CreatorName = crName }).Where(l => l.Id == log.Id).ExecuteCommandAsync();
		}
	}
}
