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;

namespace PositioningWebApp.Pages.Home.Profile
{
    public class GroupsModel : PageModel
    {
		private DevicesOnMapBackgroundContext databaseManager;
		public List<ModelGroup> Groups { get; set; }
		public GroupsModel (DevicesOnMapBackgroundContext context)
		{
			try
			{
				databaseManager = context;
			} catch (Exception ex)
			{
				throw ex;
			}
		}
		public void OnGet()
        {
			int idUser = Convert.ToInt32(Convert.ToInt32(User.Claims.ToList()[3].Value));
			List<int> idGroupsOfUser = new GroupUserService().GetGroupsOfUser(idUser, databaseManager);
			Groups = new List<ModelGroup>();
			foreach (var item in idGroupsOfUser)
			{
				Groups.Add(new GroupService().GetGroup(item, databaseManager));
			}
			
        }

		public JsonResult OnPostCreateGroup([FromBody] Select name)
		{
			int idUser = Convert.ToInt32(User.Claims.ToList()[3].Value);
			int idGroup = new GroupService().CreateNewGrop(idUser, name.Value, databaseManager);
			new GroupUserService().AddUserToGroup(idGroup, idUser, databaseManager);
			return new JsonResult(name.Value);
		}

		public JsonResult OnPostLeave([FromBody] AddToGroup ids)
		{
			int idUser = Convert.ToInt32(Convert.ToInt32(User.Claims.ToList()[3].Value));
			int idOwnerGroup = Convert.ToInt32(ids.Value);
			if (idUser == idOwnerGroup)
			{
				new GroupDeviceService().RemoveGroup(ids.IdGroup, databaseManager);
				new GroupUserService().RemoveGroup(ids.IdGroup, databaseManager);
				new GroupService().RemoveGroup(idOwnerGroup, ids.IdGroup, databaseManager);
			} else
			{
				List<ModelDevice> devices = new DeviceService().GetAllDevicesOfUser(idUser, databaseManager);
				foreach (var item in devices)
				{
					new GroupDeviceService().DeleteDeviceFromGroup(ids.IdGroup, item.Id, databaseManager);
				}
				new GroupUserService().RemoveUserFromGroup(ids.IdGroup, idUser, databaseManager);
			}
			return new JsonResult(true);
		}

	}
}