using GTANetworkAPI;
using Newtonsoft.Json;
using ReallifeGamemode.Server.Entities;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Models;
using ReallifeGamemode.Server.Services;
using ReallifeGamemode.Server.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReallifeGamemode.Server.Managers
{
    class CityHallManager : Script
    {
        private static readonly Vector3 _cityHallPosition = new Vector3(273.22, -278.14, 53.9);

        public static void LoadCityHall()
        {
            NAPI.Marker.CreateMarker(MarkerType.VerticalCylinder, _cityHallPosition.Subtract(new Vector3(0, 0, 1.7)), new Vector3(), new Vector3(), 1.0f, new Color(255, 255, 255));
            NAPI.TextLabel.CreateTextLabel("~y~Stadthalle~s~\nDrücke ~o~E~s~, um das Menü zu öffnen", _cityHallPosition, 5.0f, 1f, 0, new Color(255, 255, 255));
            var colShape = NAPI.ColShape.CreateSphereColShape(_cityHallPosition, 1.0f);
            colShape.OnEntityEnterColShape += (s, c) =>
            {
                var jobs = JobManager.GetJobs().Select(j => j.Name).ToArray();
                c.TriggerEvent("SERVER:CityHall_ShowHelpText", JsonConvert.SerializeObject(jobs));
            };

            colShape.OnEntityExitColShape += (s, c) =>
            {
                c.TriggerEvent("SERVER:CityHall_ClearHelpText");
            };
        }

        [RemoteEvent("CLIENT:CityHall_CreateGroup")]
        public void CreateGroup(Client player, string name)
        {
            using (var dbContext = new DatabaseContext())
            {
                User u = player.GetUser(dbContext);
                if(u.Group != null)
                {
                    ChatService.ErrorMessage(player, "Du bist schon in einer Gruppe");
                    return;
                }
                if(dbContext.Groups.Any(g => g.Name.ToLower() == name.ToLower()))
                {
                    ChatService.ErrorMessage(player, "Dieser Name ist schon vergeben");
                    return;
                }

                Group group = new Group
                {
                    Name = name
                };

                dbContext.Groups.Add(group);

                u.Group = group;
                u.GroupRank = GroupRank.OWNER;

                dbContext.SaveChanges();

                ChatService.BroadcastGroup($"Die Gruppe \"{name}\" wurde erfolgreich erstellt.", group);
            }
        }
    }
}
