using Microsoft.EntityFrameworkCore;
using PositioningWebApp.Models.DB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PositioningWebApp.DBServices
{
	public class LogBookService
	{
		public void AddNewLog(LogBook logBook, DevicesOnMapBackgroundContext context)
		{
			try
			{
				context.LogBook.Add(logBook);
				context.SaveChanges();
			} catch(Exception ex)
			{
				throw ex;
			}
		}

		public void EndLog(int idDevice, DateTime arrival, DevicesOnMapBackgroundContext context)
		{
			var log = context.LogBook.Where(l => l.IdDevice == idDevice && !l.Arrival.HasValue).ToList().First();
			log.Arrival = arrival;
			context.Entry(log).State = EntityState.Modified;
			context.SaveChanges();
		}

		public List<LogBook> GetLogBooks(int idDevice, DateTime from, DateTime to, DevicesOnMapBackgroundContext context)
		{
			return context.LogBook.Where(l => l.IdDevice == idDevice && from <= l.Departure.Value && l.Arrival.Value <= to)
				.OrderBy(x => x.Departure)
				.ToList();
		}

		public List<LogBook> GetLogBooks(int idDevice, DevicesOnMapBackgroundContext context)
		{
			return context.LogBook.Where(l => l.IdDevice == idDevice && l.Arrival.HasValue).ToList();
		}

		public bool FinishedTrip(int idDevice, DevicesOnMapBackgroundContext context)
		{
			var list = context.LogBook.Where(l => l.IdDevice == idDevice && !l.Arrival.HasValue).ToList();
			if (list.Count == 1)
			{
				return false;
			} else
			{
				return true;
			}
		}
	}
}
