using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using PositioningWebApp.DBServices;
using PositioningWebApp.Models.Ajax;
using PositioningWebApp.Models.DB;
using PositioningWebApp.Models.UserProfile;
using PositioningWebApp.Models.ViewModels;
using PositioningWebApp.Services;

namespace PositioningWebApp.Pages.Home
{
    public class TripsModel : PageModel
    {
		private DevicesOnMapBackgroundContext databaseManager;
		private readonly IHostingEnvironment _hostingEnvironment;
		public List<ModelTrip> Trips { get; set; }
		public TripsModel(DevicesOnMapBackgroundContext context, IHostingEnvironment hostingEnvironment)
		{
			try
			{
				databaseManager = context;
				_hostingEnvironment = hostingEnvironment;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
		public void OnGet()
        {
			int idUser = Convert.ToInt32(User.Claims.ToList()[3].Value);
			List<ModelDevice> devices = new GetAllDevices().AllSharedDevices(idUser, databaseManager);
			Trips = new List<ModelTrip>();
			foreach (var device in devices)
			{
				List<Marker> allMarkers = new PointService().GetDevicePoints(device.Id, databaseManager);
				List<Marker> consecutivelyMarkers = new List<Marker>();
				foreach (var marker in allMarkers)
				{
					if (consecutivelyMarkers.Count == 0)
					{
						consecutivelyMarkers.Add(marker);
					} else
					{
						var space = consecutivelyMarkers.Last().DateTime.Subtract(marker.DateTime).TotalMinutes;
						if ( space*(-1) < 30)
						{
							consecutivelyMarkers.Add(marker);
						} else
						{
							AddToTrips(consecutivelyMarkers, device);
							consecutivelyMarkers.Clear();
							consecutivelyMarkers.Add(marker);
						}
					}
				}
				if (consecutivelyMarkers.Count != 0)
				{
					AddToTrips(consecutivelyMarkers, device);
					consecutivelyMarkers.Clear();
				}
			}
		}

		public JsonResult OnPostShowTrip([FromBody] TripAjax trip)
		{
			DateTime start = Convert.ToDateTime(trip.Start);
			DateTime end = Convert.ToDateTime(trip.End);
			List<Marker> markers = new PointService().GetDevicePointsWhereDateIsInRange(trip.Id, start, end, databaseManager);
			return new JsonResult(markers);
		}

		public ActionResult OnPostDownload([FromBody] List<TripAjax> trips)
		{
			List<List<TripAjax>> listTrips = new List<List<TripAjax>>();
			bool added = false;
			foreach (var trip in trips)
			{
				if (listTrips.Count == 0)
				{
					List<TripAjax> tr = new List<TripAjax> { trip };
					listTrips.Add(tr);
				} else
				{
					added = false;
					foreach (var item in listTrips)
					{
						if (item.First().Identificator.Equals(trip.Identificator))
						{
							item.Add(trip);
							added = true;
							break;
						}
					}
					if (!added)
					{
						List<TripAjax> tr = new List<TripAjax> { trip };
						listTrips.Add(tr);
					}
				}
			}
			new Excel().Get(null, listTrips, _hostingEnvironment, databaseManager);
			return new JsonResult("Done");
		}

		private void AddToTrips(List<Marker> consecutivelyMarkers, ModelDevice device)
		{
			double length = new Distance().Coumpiute(consecutivelyMarkers);
			UserProfile profile = new UserService().GetUser(device.IdOwner, databaseManager);
			Trips.Add(new ModelTrip
			{
				IdDevice = device.Id,
				DeviceName = device.Name,
				EndDestination = consecutivelyMarkers.Last().LocationName,
				EndTrip = consecutivelyMarkers.Last().DateTime,
				FirstName = profile.FirstName,
				Identificator = device.Identificator,
				Length = Math.Ceiling(length),
				StartDestination = consecutivelyMarkers.First().LocationName,
				StartTrip = consecutivelyMarkers.First().DateTime,
				Surname = profile.Surname
			});
		}
    }
}