using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using AyaNova.Models;
using AyaNova.Util;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;
using Newtonsoft.Json.Linq;

namespace AyaNova.Api.Controllers
{

    /// <summary>
    ///Test controller class used during development
    /// </summary>
    [ApiController]
    [ApiVersion("8.0")]
    [Route("api/v{version:apiVersion}/trial")]
    [Produces("application/json")]
    [Authorize]
    public class TrialController : ControllerBase
    {
        private readonly AyContext ct;
        private readonly ILogger<WidgetController> log;
        private readonly ApiServerState serverState;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="dbcontext"></param>
        /// <param name="logger"></param>
        /// <param name="apiServerState"></param>
        public TrialController(AyContext dbcontext, ILogger<WidgetController> logger, ApiServerState apiServerState)
        {
            ct = dbcontext;
            log = logger;
            serverState = apiServerState;
        }


        /// <summary>
        /// Seed a trial database with sample data.
        /// 
        /// You can control the size and scope of the seeded data with the passed in size value
        /// "Small" - a small one man shop dataset
        /// "Medium" - Local service company with multiple employees and departments dataset
        /// "Large" - Large corporate multi regional dataset
        /// "Huge" - Used for automated testing and development, if you choose this it will take a very long time (15 minutes to overnight)
        /// </summary>
        /// <param name="size">Valid values are "Small", "Medium", "Large", "Huge"</param>
        /// <param name="timeZoneOffset">Value in hours of local time zone offset from UTC / GMT. This ensures that data is generated relative to the desired time zone</param>
        /// <returns>Job Id</returns>
        [HttpPost("seed/{size}/{timeZoneOffset}")]
        public async Task<IActionResult> SeedTrialDatabase([FromRoute] string size, [FromRoute] decimal timeZoneOffset)
        {
            if (serverState.IsClosed)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

            if (!ModelState.IsValid)
            {
                return BadRequest(new ApiErrorResponse(ModelState));
            }

            if (!AyaNova.Core.License.ActiveKey.TrialLicense)
            {
                return BadRequest(new ApiErrorResponse(ApiErrorCode.INVALID_OPERATION, null, "Current license is not a trial license key.  Only a trial can be seeded."));
            }

            Seeder.Level.SeedLevel seedLevel = Seeder.Level.StringToSeedLevel(size);
            if (seedLevel == Seeder.Level.SeedLevel.NotValid)
                return BadRequest(new ApiErrorResponse(ApiErrorCode.NOT_FOUND, "size", "Valid values are \"small\", \"medium\", \"large\", \"huge\""));

            //Create the job here

            JObject o = JObject.FromObject(new
            {
                seedLevel = seedLevel,
                timeZoneOffset = timeZoneOffset
            });

            OpsJob j = new OpsJob();
            j.Name = $"Seed test data (size={size})";
            j.JobType = JobType.SeedTestData;
            j.Exclusive = true;//don't run other jobs, this will erase the db
            j.JobInfo = o.ToString();
            await JobsBiz.AddJobAsync(j);

            //Log
            await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserIdFromContext.Id(HttpContext.Items), 0, AyaType.TrialSeeder, AyaEvent.Created, size), ct);

            return Accepted(new { JobId = j.GId });//202 accepted
        }



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


    }//eoc
}//eons