using System;
using System.Collections.Generic;
using System.Text;
using ReallifeGamemode.Server.Core.API;
using ReallifeGamemode.Server.Types;
using ReallifeGamemode.Server.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace ReallifeGamemode.Server.Core.Menus
{
  internal class PoliceDepartment : Script
  {


    public PoliceDepartment()
    {
      // Marker position: 440.869 -981.045 30.689

      CreateVisuals();

      EventHandler.RegisterClientEvent("PoliceDepartment_MenuSelect", OnMenuSelect);
    }

    private void OnMenuSelect(IPlayer player, object[] args)
    {
      var index = (long)args[0];

      using (var dbContext = GetDbContext())
      {
        var user = player.GetUser(dbContext, bankAccount: true);

        if (index == 0)
        {
          if (user.WeaponLicense)
          {
            player.SendMessage("Du besitzt schon einen Waffenschein.", ChatPrefix.Info);
            return;
          }

          var account = user.BankAccount;

          if (account.Balance < 5000)
          {
            player.SendMessage("Du hast nicht genug Geld auf der Bank (5.000$)!", ChatPrefix.Error);
            return;
          }

          account.Balance -= 5000;

          player.SendMessage("Du hast den Waffenschein erfolgreich erworben.", ChatPrefix.Info);

          dbContext.Factions.Include(f => f.BankAccount).Where(f => f.Id == 1).First().BankAccount.Balance += 1000;
          dbContext.Factions.Include(f => f.BankAccount).Where(f => f.Id == 3).First().BankAccount.Balance += 1000;

          user.WeaponLicense = true;
          dbContext.SaveChanges();
        }
      }
    }

    private void CreateVisuals()
    {
      Position pos = new Position(12.7499, -1105.1168, 29.797);

      Api.TextLabel.CreateTextLabel("Waffenschein kaufen\n\nDrücke ~y~E~s~, um das Menü zu öffnen", pos, 20f, 1.3f, Font.ChaletLondon, Color.White);
      Api.Marker.CreateMarker(MarkerType.VerticalCylinder, pos.Subtract(new Position(0, 0, 1.7)), new Position(), new Position(), 1f, Color.White);
      IColShape colShape = Api.ColShape.CreateSphere(pos, 2f);

      colShape.OnEntityEnter += OnPlayerEnterPoliceDepartment;
      colShape.OnEntityExit += OnPlayerExitPoliceDepartment;
    }

    private void OnPlayerEnterPoliceDepartment(IColShape colShape, IPlayer player)
    {
      if (player.IsInVehicle)
      {
        return;
      }

      player.TriggerEvent("PoliceDepartment_EnterColShape");
    }

    private void OnPlayerExitPoliceDepartment(IColShape colShape, IPlayer player)
    {
      if (player.IsInVehicle)
      {
        return;
      }

      player.TriggerEvent("PoliceDepartment_ExitColShape");
    }
  }
}
