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

namespace PositioningWebApp.Pages.Home.Zone
{
    public class EditZoneModel : PageModel
    {
		private DevicesOnMapBackgroundContext databaseManager;
		[BindProperty]
		public ModelZone ZoneViewModel { get; set; }
		public List<ModelDevice> DeviceZone { get; set; }
		public List<Marker> Markers { get; set; }
		public EditZoneModel(DevicesOnMapBackgroundContext context)
		{
			try
			{
				databaseManager = context;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
		public void OnGet(int id)
        {
			var idOwner = Convert.ToInt32(Convert.ToInt32(User.Claims.ToList()[3].Value));
			ZoneViewModel = new ZoneService().GetZoneBasedOnId(id, databaseManager);
			Markers = new PointService().GetZonePointsBasedOnIDZone(id, databaseManager);
        }

		public JsonResult OnPostMarkers([FromBody] string id)
		{
			return new JsonResult(new PointService().GetZonePointsBasedOnIDZone(Convert.ToInt32(id), databaseManager));
		}

		public JsonResult OnPostEditZone([FromBody] ZonePoints points)
		{
			int idZone = Convert.ToInt32(points.Identificator);
			new ZoneService().UpdateZoneName(idZone, points.Name, databaseManager);
			foreach (var item in points.Points)
			{
				if (item.Action != null)
				{
					if (item.Action.Equals("created"))
					{
						new PointService().AddSingleZonePoint(idZone, item.Latitude, item.Longitude, databaseManager);
					}
					if (item.Action.Equals("updated"))
					{
						new PointService().UpdatePoint(item.IdMarker, item.Latitude, item.Longitude, databaseManager);
					}
					if (item.Action.Equals("deleted"))
					{
						new PointService().DeletePoint(item.IdMarker, databaseManager);
					}
				}
			}
			return new JsonResult(true);
		}

    }
}