using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using sodoff.Attributes;
using sodoff.Model;

namespace sodoff.Controllers.Common
{
    [ApiController]
    public class PrecenseController : Controller
    {
        private readonly DBContext ctx;
        public PrecenseController(DBContext ctx) => this.ctx = ctx;

        [HttpPost]
        [Produces("application/json")]
        [Route("Precense/SetVikingOnline")]
        public IActionResult SetVikingOnline([FromForm] Guid token, [FromForm] bool online)
        {
            // get viking from session
            Viking? viking = ctx.Sessions.FirstOrDefault(e => e.ApiToken == token)?.Viking;

            if (viking != null)
            {
                viking.Online = online;
                ctx.SaveChanges();
                return Ok(viking.Online);
            } else return Ok(false);
        }

        [HttpPost]
        [Produces("application/json")]
        [Route("Precense/SetVikingRoom")]
        public IActionResult SetVikingRoom([FromForm] Guid token, [FromForm] int roomId, [FromForm] string zoneName)
        {
            // get viking from session
            Viking? viking = ctx.Sessions.FirstOrDefault(e => e.ApiToken == token)?.Viking;

            if (viking != null)
            {
                if (roomId <= 0 && string.IsNullOrEmpty(zoneName))
                {
                    viking.CurrentRoomId = null;
                    viking.CurrentZone = null;
                    ctx.SaveChanges();
                    return Ok(true);
                }

                viking.CurrentRoomId = roomId;
                viking.CurrentZone = zoneName;
                ctx.SaveChanges();
                return Ok(true);
            }
            else return Ok(false);
        }
    }
}
