using Microsoft.EntityFrameworkCore;
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 ZoneService
	{
		public List<ModelZone> GetAllZonesUserBasedOnID (int ownerId, DevicesOnMapBackgroundContext context)
		{
			var zones = from z in context.Zones where z.OwnerId == ownerId select z;
			List<ModelZone> ret = new List<ModelZone>();
			foreach (var item in zones.ToList())
			{
				ret.Add(
					new ModelZone
					{
						
						Id = item.Id,
						Title = item.Title,
						
					});
			}
			return ret;
		}

		public int AddZone(string title, int ownerID, DevicesOnMapBackgroundContext context)
		{
			context.Zones.Add(new Zones
			{
				OwnerId = ownerID,
				Title = title
			});
			context.SaveChanges();

			var zones = from z in context.Zones where ownerID == z.OwnerId || title == z.Title select z.Id;
			return zones.ToList().Last();
		}

		public ModelZone GetZoneBasedOnId(int idZone, DevicesOnMapBackgroundContext context)
		{
			var zone = (from z in context.Zones where z.Id == idZone select z).ToList().First();
			ModelZone ret = new ModelZone
			{
				Id = zone.Id,
				Title = zone.Title,
			};
			return ret;
		}

		public void UpdateZoneName(int idZone, string title, DevicesOnMapBackgroundContext context)
		{
			var zone = context.Zones.FirstOrDefault(z => z.Id == idZone);
			if (zone != null)
			{
				zone.Title = title;
			};
			context.Entry(zone).State = EntityState.Modified;
			context.SaveChanges();
		}

		public void DeleteZone(int idZone, DevicesOnMapBackgroundContext context)
		{
			var zone = (from z in context.Zones where z.Id == idZone select z).ToList();
			if (zone.Count != 0)
			{
				context.Zones.Remove(zone.First());
				context.SaveChanges();
			}
		}
	}
}
