using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PositioningWebApp.DBServices;
using PositioningWebApp.Models.Api;
using PositioningWebApp.Models.DB;
using PositioningWebApp.Models.ViewModels;

namespace PositioningWebApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LogBookController : ControllerBase
    {
		private readonly DevicesOnMapBackgroundContext databaseManager;

		public LogBookController(DevicesOnMapBackgroundContext context)
		{
			databaseManager = context;
		}
		// GET: api/LogBook
		[HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/LogBook/5
        [HttpGet("{id}", Name = "Get")]
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/LogBook
        [HttpPost]
        public void Post([FromBody] LogBookPost logBook)
        {
			DateTime dateTime;
			if (logBook.DateTime.HasValue)
			{
				dateTime = logBook.DateTime.Value;
			} else
			{
				dateTime = DateTime.Now;
			}
			ModelDevice device = new DeviceService().GetDeviceBasedOnIdentificator(logBook.Identificator, databaseManager);
			if (!new LogBookService().FinishedTrip(device.Id, databaseManager))
			{
				new LogBookService().EndLog(device.Id, dateTime, databaseManager);
			} else
			{
				LogBook book = new LogBook
				{
					Departure = dateTime,
					Purpose = logBook.Purpos,
					IdDevice = device.Id
				};
				new LogBookService().AddNewLog(book, databaseManager);
			}
        }

        // PUT: api/LogBook/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE: api/ApiWithActions/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
