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

namespace PositioningWebApp.Pages.Home.Zone
{
    public class ZoneModel : PageModel
    {
		private DevicesOnMapBackgroundContext databaseManager;
		[BindProperty]
		public ModelZone ZoneViewModel { get; set; }
		[BindProperty]
		public List<ModelZone> ListZones { get; set; }
		public List<ModelDevice> DeviceZone { get; set; }
		public ZoneModel(DevicesOnMapBackgroundContext context)
		{
			try
			{
				databaseManager = context;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
		public void OnGet()
        {
			var id = Convert.ToInt32(User.Claims.ToList()[3].Value);
			ListZones = new ZoneService().GetAllZonesUserBasedOnID(id, databaseManager);
			DeviceZone = new DeviceService().GetAllDevicesOfUserWhereZoneIsNull(id, databaseManager);
		}
		
		public JsonResult OnPostSave([FromBody] ZonePoints s)
		{
			var id = Convert.ToInt32(User.Claims.ToList()[3].Value);
			
			ZoneService zoneService = new ZoneService();
			int idZone = zoneService.AddZone(s.Name, id, databaseManager);
			if (s.Identificator != "")
			{
				var device = new DeviceService().GetDeviceBasedOnIdentificator(s.Identificator, databaseManager);
				new DeviceZoneService().CreateZoneDeviceConnection(device.Id, idZone, databaseManager);
			}
			new PointService().AddPointsForZone(s.Points.ToList(), idZone, databaseManager);
			return new JsonResult("Done");

		}

		public JsonResult OnPostDeleteZone([FromBody] Select idZone)
		{
			int id = Convert.ToInt32(idZone.Value);

			new PointService().DeleteZonePoints(id, databaseManager);
			new ZoneService().DeleteZone(id, databaseManager);
			return new JsonResult(true);
		}
	}
}