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

namespace PositioningWebApp.DBServices
{
	public class GroupDeviceService
	{
		public void AddDeviceIntoGroup(int idGroup, int idDevie, DevicesOnMapBackgroundContext context)
		{
			context.GroupDevice.Add(new GroupDevice {
				Iddevice = idDevie,
				Idgroup = idGroup
			});
			context.SaveChanges();
		}

		public List<int> GetIdDevicesInGroup(int idGroup, DevicesOnMapBackgroundContext context)
		{
			var idDevices = from g in context.GroupDevice where g.Idgroup == idGroup select g.Iddevice.Value;
			return idDevices.ToList();
		}

		public List<int> GetIdGroup(int idDevice, DevicesOnMapBackgroundContext context)
		{
			var idGroups = from g in context.GroupDevice where g.Iddevice == idDevice select g.Idgroup.Value;
			return idGroups.ToList();
		}

		public void DeleteDeviceFromGroup(int idGroup, int idDevice, DevicesOnMapBackgroundContext context)
		{
			var toDelete = context.GroupDevice.Where(g => g.Idgroup == idGroup && g.Iddevice == idDevice);
			if (toDelete.ToList().Count != 0)
			{
				context.GroupDevice.Remove(toDelete.ToList().First());
				context.SaveChanges();
			}
		}

		public void RemoveGroup(int idGroup, DevicesOnMapBackgroundContext context)
		{
			var toDelete = context.GroupDevice.Where(g => g.Idgroup == idGroup).ToList();
			if (toDelete.Count != 0)
			{
				foreach (var item in toDelete.ToList())
				{
					context.GroupDevice.Remove(item);
				}
				context.SaveChanges();
			}
		}

		public void RemoveDevice(int idDevcice, DevicesOnMapBackgroundContext context)
		{
			var toDelete = context.GroupDevice.Where(g => g.Iddevice == idDevcice).ToList();
			if (toDelete.Count != 0)
			{
				foreach (var item in toDelete)
				{
					context.GroupDevice.Remove(item);
				}
				context.SaveChanges();
			}
		}
	}
}
