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

namespace PositioningWebApp.DBServices
{
	public class DeviceZoneService
	{
		public void CreateZoneDeviceConnection(int idDevice, int idZone, DevicesOnMapBackgroundContext context)
		{
			context.DeviceZone.Add(new DeviceZone
			{
				IdDevice = idDevice,
				IdZone = idZone
			});
			context.SaveChanges();
		}

		public void DeleteConection(int idDevice, int idZone, DevicesOnMapBackgroundContext context)
		{
			var toDel = context.DeviceZone.Where(d => d.IdDevice == idDevice && d.IdZone == idZone).ToList();
			if (toDel.Count != 0)
			{
				context.DeviceZone.Remove(toDel.First());
				context.SaveChanges();
			}
		}

		public List<int> GetDeviceZone(int idDevice, DevicesOnMapBackgroundContext context)
		{
			var list = context.DeviceZone.Where(d => d.IdDevice == idDevice).ToList();
			List<int> ret = new List<int>();
			foreach (var item in list)
			{
				ret.Add(item.IdZone.Value);
			}
			return ret;
		}

		public List<int> GetDeviceZones(int idZone, DevicesOnMapBackgroundContext context)
		{
			var list =  context.DeviceZone.Where(d => d.IdZone == idZone).ToList();
			List<int> ret = new List<int>();
			foreach (var item in list)
			{
				ret.Add(item.IdDevice.Value);
			}
			return ret;
		}

		public void DeleteZone(int idZone, DevicesOnMapBackgroundContext context)
		{
			var list = context.DeviceZone.Where(d => d.IdZone == idZone).ToList();
			if (list.Count != 0)
			{
				foreach (var item in list)
				{
					context.DeviceZone.Remove(item);
				}
				context.SaveChanges();
			}
		}

		public bool ConnectionExist(int idZone, int idDevie, DevicesOnMapBackgroundContext context)
		{
			var l = context.DeviceZone.Where(d => d.IdZone == idZone && idDevie == d.IdDevice).ToList();
			if (l.Count == 0)
			{
				return false;
			} else
			{
				return true;
			}
		}

		public void DeleteDevice(int idDevice, DevicesOnMapBackgroundContext context)
		{
			var list = context.DeviceZone.Where(d => d.IdDevice == idDevice).ToList();
			if (list.Count != 0)
			{
				foreach (var item in list)
				{
					context.DeviceZone.Remove(item);
				}
			}
		}
	}
}
