using PositioningWebApp.DBServices;
using PositioningWebApp.Models.Api;
using PositioningWebApp.Models.DB;
using PositioningWebApp.Models.ViewModels;
using System.Collections.Generic;

namespace PositioningWebApp.Services
{
	public class InZone
	{
		public bool IsDeviceInsideZones(List<int> zones, Point location, DevicesOnMapBackgroundContext context)
		{
			bool ret = false;
			foreach (var idZone in zones)
			{
				List<Marker> markers = new PointService().GetZonePointsBasedOnIDZone(idZone, context);
				if (IsDeviceInsideZone(markers, location))
				{
					ret = true;
					break;
				}
			}
			return ret;
		}

		private bool IsDeviceInsideZone(List<Marker> zone, Point newDeviceLocation)
		{
			int i, j = 0;
			bool ret = false;
			for (i = 0, j = zone.Count - 1; i < zone.Count; j = i++)
			{
				if (((zone[i].Latitude > newDeviceLocation.Latitude) != (zone[j].Latitude > newDeviceLocation.Latitude)) &&
				 (newDeviceLocation.Longitude < (zone[j].Longitude - zone[i].Longitude) * 
				 (newDeviceLocation.Latitude - zone[i].Latitude) / (zone[j].Latitude - zone[i].Latitude) + zone[i].Longitude))
					ret = !ret;
			}
			return ret;
		}
	}
}
