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 Microsoft.EntityFrameworkCore;
using System.Linq;
using Sockeye.Models;
using Sockeye.Api.ControllerHelpers;
using Sockeye.Biz;
using System.Text;
using System;


namespace Sockeye.Api.Controllers
{
    [ApiController]
    [ApiVersion("8.0")]
    [Route("api/v{version:apiVersion}/license")]
    [Produces("application/json")]
    [Authorize]
    public class LicenseController : ControllerBase
    {
        private readonly AyContext ct;
        private readonly ILogger<LicenseController> log;
        private readonly ApiServerState serverState;

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

        /// <summary>
        /// Create License
        /// </summary>
        /// <param name="newObject"></param>
        /// <param name="apiVersion">From route path</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PostLicense([FromBody] License newObject, ApiVersion apiVersion)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            LicenseBiz biz = LicenseBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasCreateRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            License o = await biz.CreateAsync(newObject);
            if (o == null)
                return BadRequest(new ApiErrorResponse(biz.Errors));
            else
                return CreatedAtAction(nameof(LicenseController.GetLicense), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o));
        }


        /// <summary>
        /// Get License
        /// </summary>
        /// <param name="id"></param>
        /// <returns>License</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetLicense([FromRoute] long id)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            LicenseBiz biz = LicenseBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasReadFullRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            var o = await biz.GetAsync(id);
            if (o == null) return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
            return Ok(ApiOkResponse.Response(o));
        }

        /// <summary>
        /// Update License
        /// </summary>        
        /// <param name="updatedObject"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> PutLicense([FromBody] License updatedObject)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            LicenseBiz biz = LicenseBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasModifyRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            var o = await biz.PutAsync(updatedObject);
            if (o == null)
            {
                if (biz.Errors.Exists(z => z.Code == ApiErrorCode.CONCURRENCY_CONFLICT))
                    return StatusCode(409, new ApiErrorResponse(biz.Errors));
                else
                    return BadRequest(new ApiErrorResponse(biz.Errors));
            }
            return Ok(ApiOkResponse.Response(o)); //Must return entire object on put as server modifies license on update
        }

        /// <summary>
        /// Delete License
        /// </summary>
        /// <param name="id"></param>
        /// <returns>NoContent</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteLicense([FromRoute] long id)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            LicenseBiz biz = LicenseBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasDeleteRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!await biz.DeleteAsync(id))
                return BadRequest(new ApiErrorResponse(biz.Errors));
            return NoContent();
        }



        //v7 backdoor password generator

        /// <summary>
        /// Get v7 reset manager auth code logins
        /// </summary>       
        /// <returns>override creds</returns>
        [HttpGet("v7-reset-manager-creds")]
        public ActionResult GetBackDoor()
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            LicenseBiz biz = LicenseBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasReadFullRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));


            return Ok(ApiOkResponse.Response(new
            {
                today = Generate(DateTime.Today, new Random(unchecked((int)DateTime.Now.Ticks))),
                tomorrow = Generate(DateTime.Today.AddDays(1), new Random(~unchecked((int)DateTime.Now.Ticks)))
            }));
        }

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




        private string Generate(DateTime dtWhen, Random r)
        {
            int nDummyCharFactor = 4;
            int ndwf = 0;
            StringBuilder sb = new StringBuilder();
            string sLogin = "";
            string sPassword = "";
            switch (dtWhen.DayOfWeek)
            {
                case System.DayOfWeek.Monday:
                    ndwf = 12;
                    break;
                case System.DayOfWeek.Tuesday:
                    ndwf = 49;
                    break;
                case System.DayOfWeek.Wednesday:
                    ndwf = 23;
                    break;
                case System.DayOfWeek.Thursday:
                    ndwf = 65;
                    break;
                case System.DayOfWeek.Friday:
                    ndwf = 87;
                    break;
                case System.DayOfWeek.Sunday:
                    ndwf = 99;
                    break;
                case System.DayOfWeek.Saturday:
                    ndwf = 72;
                    break;

            }
            int nLogin = dtWhen.DayOfYear + ndwf * ndwf;
            int nPassword = (dtWhen.Year + dtWhen.Month + ndwf) * (ndwf + 2);


            char dummy = ' ';
            foreach (char c in nLogin.ToString())
            {
                int nDummycharcount = r.Next(nDummyCharFactor) + 1;
                for (int x = 0; x < nDummycharcount; x++)
                {
                    dummy = (char)(r.Next(26) + 65);
                    sLogin += dummy;


                }
                sLogin += c;
            }
            sb.Append("Login:[");
            sb.Append(sLogin);
            sb.Append("]\r\n");


            //Do password

            foreach (char c in nPassword.ToString())
            {
                int nDummycharcount = r.Next(nDummyCharFactor) + 1;
                for (int x = 0; x < nDummycharcount; x++)
                {
                    dummy = (char)(r.Next(26) + 65);
                    sPassword += dummy;


                }
                sPassword += c;
            }
            sb.Append("Password:[");
            sb.Append(sPassword);
            sb.Append("]\r\n");

            return sb.ToString();
        }

    }//eoc

}//eons