using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using App.Metrics;
using AyaNova.Models;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;


namespace AyaNova.Api.Controllers
{

    /// <summary>
    /// Log files controller
    /// </summary>
    [ApiVersion("8.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [Authorize]
    public class MetricsController : Controller
    {
        private readonly AyContext ct;
        private readonly ILogger<LogFilesController> log;
        private readonly ApiServerState serverState;
        private readonly IMetrics metrics;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="dbcontext"></param>
        /// <param name="logger"></param>
        /// <param name="apiServerState"></param>
        /// <param name="Metrics"></param>
        public MetricsController(AyContext dbcontext, ILogger<LogFilesController> logger, ApiServerState apiServerState, IMetrics Metrics)
        {
            ct = dbcontext;
            log = logger;
            serverState = apiServerState;
            metrics = Metrics;
        }


        /// <summary>
        /// Get metrics as text document
        /// 
        /// Required roles:
        /// OpsAdminFull | OpsAdminLimited
        /// </summary>        
        /// <returns>Snapshot of metrics</returns>
        [HttpGet("TextSnapShot")]
        public async Task<IActionResult> GetMetrics()
        {
            //Open or opsOnly and user is opsadminfull or opsadminlimited
            if (!serverState.IsOpenOrOpsOnly || (serverState.IsOpsOnly && !Authorized.HasAnyRole(HttpContext.Items, AuthorizationRoles.OpsAdminFull | AuthorizationRoles.OpsAdminLimited)))
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

            if (!Authorized.IsAuthorizedToReadFullRecord(HttpContext.Items, AyaType.Metrics))
            {
                return StatusCode(401, new ApiNotAuthorizedResponse());
            }

            string sResult = await GetTheMetrics("plain");

            //Log
            EventLogProcessor.LogEventToDatabase(new Event(UserIdFromContext.Id(HttpContext.Items), 0, AyaType.Metrics, AyaEvent.Retrieved), ct);

            return Content(sResult);
        }


        /// <summary>
        /// Get metrics as json object
        /// 
        /// Required roles:
        /// OpsAdminFull | OpsAdminLimited
        /// </summary>        
        /// <returns>Snapshot of metrics</returns>
        [HttpGet("JsonSnapShot")]
        public async Task<IActionResult> GetJsonMetrics()
        {
            //Open or opsOnly and user is opsadminfull or opsadminlimited
            if (!serverState.IsOpenOrOpsOnly || (serverState.IsOpsOnly && !Authorized.HasAnyRole(HttpContext.Items, AuthorizationRoles.OpsAdminFull | AuthorizationRoles.OpsAdminLimited)))
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

            if (!Authorized.IsAuthorizedToReadFullRecord(HttpContext.Items, AyaType.Metrics))
            {
                return StatusCode(401, new ApiNotAuthorizedResponse());
            }

            string sResult = await GetTheMetrics("json");
            JObject json = JObject.Parse(sResult);

            //Log
            EventLogProcessor.LogEventToDatabase(new Event(UserIdFromContext.Id(HttpContext.Items), 0, AyaType.Metrics, AyaEvent.Retrieved), ct);
           
            return Ok(new ApiOkResponse(json));
        }

        /// <summary>
        /// Get the metrics snapshot
        /// </summary>
        /// <param name="format">Either "json" for json format or "plain" for plaintext format</param>
        /// <returns></returns>
        private async Task<string> GetTheMetrics(string format)
        {
            var snapshot = metrics.Snapshot.Get();

            var formatters = ((IMetricsRoot)metrics).OutputMetricsFormatters;
            string sResult = $"ERROR GETTING METRICS IN {format} FORMAT";

            foreach (var formatter in formatters)
            {
                if (formatter.MediaType.Format == format)
                {
                    using (var stream = new MemoryStream())
                    {
                        await formatter.WriteAsync(stream, snapshot);
                        sResult = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                    }
                }
            }

            return sResult;
        }


        //------------


    }
}