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

namespace PositioningWebApp.Controllers
{
	[Route("api/Point")]
	public class PointController : Controller
	{
		private readonly DevicesOnMapBackgroundContext databaseManager;

		public PointController (DevicesOnMapBackgroundContext context)
		{
			databaseManager = context;
		}

		// GET: api/<controller>
		[HttpGet]
		public IEnumerable<string> Get()
		{
			return new string[] { "value1", "value2" };
		}

		// GET api/<controller>/5
		[HttpGet("{id}")]
		public string Get(int id)
		{
			return "value";
		}

		// POST api/<controller>
		[HttpPost]
		public void Post([FromBody]Point item)
		{
			ModelDevice device = new DeviceService().GetDeviceBasedOnIdentificator(item.Identificator, databaseManager);
			if(device != null)	
			{
				new PointService().AddPointFromApi(item, device.Id, new PointLocation().Get(item.Latitude, item.Longitude), databaseManager);
				List<int> zones = new DeviceZoneService().GetDeviceZone(device.Id, databaseManager);
				if (zones.Count != 0 && new LogBookService().FinishedTrip(device.Id, databaseManager))
				{
					if (!new InZone().IsDeviceInsideZones(zones, item, databaseManager))
					{
						
						List<int> idGroups = new GroupDeviceService().GetIdGroup(device.Id, databaseManager);
						List<int> idUsers = new List<int>();
						List<int> idUsersDupli = new GroupUserService().GetUserIDsFromGroups(idGroups, databaseManager);
						
						foreach (var idU in idUsersDupli)
						{
							if (!idUsers.Contains(idU))
							{
								idUsers.Add(idU);
							}
						}
						
						List<UserProfile> profiles = new UserService().GetProfiles(idUsers, databaseManager);
						if (device.AlertEmail.Equals("True"))
						{
							new Email().SendEmail(profiles, device, item);
						}
						if (device.AlertSMS.Equals("True"))
						{
							// SMS allert
						}
						new DeviceService().UpdateSendedAlert(device.Id, true, databaseManager);
					} else
					{
						if (device.AlertSended.HasValue)
						{
							if (device.AlertSended.Value)
							{
								new DeviceService().UpdateSendedAlert(device.Id, false, databaseManager);
							}
						}
					}
				}
			}
		}

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

		// DELETE api/<controller>/5
		[HttpDelete("{id}")]
		public void Delete(int id)
		{
		}
	}
}
