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.Ajax;
using PositioningWebApp.Models.DB;
using PositioningWebApp.Models.ViewModels;
using PositioningWebApp.Services;

namespace PositioningWebApp.Pages.Home.Profile
{
    public class EditDeviceModel : PageModel
    {
		private DevicesOnMapBackgroundContext context;
		public ModelDevice Model { get; set; }
		public List<ModelZone> ListZone { get; set; }
		public List<int> ActiveZones { get; set; }

		public EditDeviceModel(DevicesOnMapBackgroundContext _context)
		{
			try
			{
				this.context = _context;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
		public void OnGet(int id)
        {
			var idOwner = Convert.ToInt32(Convert.ToInt32(User.Claims.ToList()[3].Value));
			ListZone = new ZoneService().GetAllZonesUserBasedOnID(idOwner, context);
			Model = new DeviceService().GetDeviceBasedOnIdDevice(id, context);
			
			ActiveZones = new DeviceZoneService().GetDeviceZone(id, context);
        }

		public JsonResult OnPostUpdateDevice([FromBody] DeviceAjax device)
		{
			var email = false;
			var phone = false;
			if (device.AlertEmail.Equals("true"))
			{
				email = true;
			}
			if (device.AlertSMS.Equals("true"))
			{
				phone = true;
			}
			Devices d = new Devices
			{
				Id = device.Id,
				Title = device.Name,
				Identifier = device.Identificator,
				ZoneEmailAlert = email,
				ZoneSmsalert = phone
			};
			foreach (var item in device.ZoneId)
			{
				if (item.Status.Equals("True"))
				{
					if (!new DeviceZoneService().ConnectionExist(Convert.ToInt32(item.Id), device.Id, context))
					{
						new DeviceZoneService().CreateZoneDeviceConnection(device.Id, Convert.ToInt32(item.Id), context);
					}
				} else
				{
					if (new DeviceZoneService().ConnectionExist(Convert.ToInt32(item.Id), device.Id, context))
					{
						new DeviceZoneService().DeleteConection(device.Id, Convert.ToInt32(item.Id), context);
					}
				}
			}
			
			new DeviceService().UpdateDeviceBasedOnIdDevice(d, context);
			return new JsonResult("Done");
		}
    } 
}