using Microsoft.AspNetCore.Mvc;
using sodoff.Model;
using sodoff.Util;

namespace sodoff.Controllers.Common
{
    public class AnalyticsController : Controller
    {
        private readonly DBContext ctx;
        public AnalyticsController(DBContext ctx)
        {
            this.ctx = ctx;
        }

        [HttpGet]
        [Route("AnalyticsWebService.asmx/GetUserAndVikingCount")]
        public IActionResult GetUserAndVikingCount(bool vikingsOnly)
        {
            if (vikingsOnly) return Ok(new UserStatistics
            {
                VikingCount = ctx.Vikings.Count(e => e.Id > 0)
            });
            else return Ok(new UserStatistics
            {
                VikingCount = ctx.Vikings.Count(),
                UserCount = ctx.Users.Count(),
            });
        }

        [HttpPost]
        [Produces("application/xml")]
        [Route("AnalyticsWebService.asmx/LogEvent")]
        public IActionResult LogEvent([FromForm] string eventXml)
        {
            DateTime now = DateTime.UtcNow;
            Schema.LogEvent? eventClass = XmlUtil.DeserializeXml<Schema.LogEvent>(eventXml);
            string eventToLog = $"---\nEvent Logged At {now.ToLocalTime()}\nUserID - {eventClass.UserID}\nEvent Category ID - {eventClass.EventCategoryID}\nEvent Type ID - {eventClass.EventTypeID}\nEvent Data - {eventClass.Data}\n---";

            Console.WriteLine(eventToLog);

            return Ok(true);
        }

        [Route("ping")]
        [Route("ContentWebService.asmx")] // ping URL used by SoD
        public IActionResult Ping()
        {
            return Ok();
        }
    }

    public class UserStatistics
    {
        public int VikingCount { get; set; }
        public int? UserCount { get; set; }
    }
}