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 DeviceModel : PageModel
    {
		private DevicesOnMapBackgroundContext context;
		[BindProperty]
		public List<ModelDevice> ListDevices { get; set; }
		public ModelDevice Model { get; set; }
		public List<ModelZone> ListZone { get; set; }
		public DeviceModel(DevicesOnMapBackgroundContext _context)
		{
			try
			{
				this.context = _context;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
		public void OnGet()
        {
			var id = Convert.ToInt32(Convert.ToInt32(User.Claims.ToList()[3].Value));
			ListDevices = new DeviceService().GetAllDevicesOfUser(id, context);
			ListZone = new ZoneService().GetAllZonesUserBasedOnID(id, context);
		}

		public JsonResult OnPostDeleteDevice([FromBody] string id)
		{
			int idDevice = Convert.ToInt32(id);
			new PointService().DeletePointsBasedOnDeviceID(idDevice, context);
			new GroupDeviceService().RemoveDevice(idDevice, context);
			new DeviceZoneService().DeleteDevice(idDevice, context);
			new DeviceService().DeleteDeviceBasedOnDeviceId(idDevice, context);
			return new JsonResult("return");
		}

		public JsonResult OnPostSaveDevice([FromBody] DeviceAjax model)
		{
			int ownerID = Convert.ToInt32(Convert.ToInt32(User.Claims.ToList()[3].Value));
			bool emailAlert = false;
			bool smsAlert = false;
			if (model.AlertEmail.Equals("True"))
			{
				emailAlert = true;
			}
			if (model.AlertSMS.Equals("True"))
			{
				smsAlert = true;
			}
			Devices device = null;
			if (model.ZoneId.First().Id.Equals("null"))
			{
				device = new Devices
				{

					OwnerId = ownerID,
					Title = model.Name,
					ZoneEmailAlert = emailAlert,
					ZoneSmsalert = smsAlert
				};
				device.Identifier = Identificator();
				int id = new DeviceService().AddDevice(device, context);
			}
			else
			{
				device = new Devices
				{
					OwnerId = ownerID,
					Title = model.Name,
					ZoneEmailAlert = emailAlert,
					ZoneSmsalert = smsAlert
				};
				device.Identifier = Identificator();
				int id = new DeviceService().AddDevice(device, context);
				new DeviceZoneService().CreateZoneDeviceConnection(id, Convert.ToInt32(model.ZoneId.First().Id), context);
			}
			return new JsonResult("return");
		}

		private string Identificator()
		{
			List<string> idetificators = new DeviceService().GetDevicesIndetificators(context);
			Generator generator = new Generator();
			while (true)
			{
				var temp = generator.Identificator();
				if (!idetificators.Contains(temp))
				{
					return temp;
				}
			}
		}

	}
}