using System.Collections.Generic;
using System.Linq;
using GTANetworkAPI;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Services;
using ReallifeGamemode.Server.Extensions;


namespace ReallifeGamemode.Server.Job
{
  public abstract class JobBase : Script
  {
    public delegate void JobStartHandler(Player player);

    public delegate void JobStopHandler(Player player);

    public event JobStartHandler JobStart;

    public event JobStopHandler JobStop;

    private readonly List<Player> _inJob = new List<Player>();
    private static readonly List<Player> jobPlayer = new List<Player>();

    public abstract int Id { get; }

    public abstract string Name { get; }

    public abstract bool NeedVehicleToStart { get; }

    public void StartJob(Player player)
    {
      if (_inJob.Contains(player)) return;
      _inJob.Add(player);
      jobPlayer.Add(player);

      ChatService.SendMessage(player, $"~y~[JOB]~s~ Du hast deinen Job ~o~{this.Name}~s~ gestartet.");

      JobStart?.Invoke(player);
    }

    public void StopJob(Player player, bool quit = false)
    {
      if (!_inJob.Contains(player)) return;
      _inJob.Remove(player);
      jobPlayer.Remove(player);

      

      User user = player.GetUser();

      using (var dbContext = new DatabaseContext())
      {
        user = player.GetUser(dbContext);
        user.trashcount -= user.trashcount;
        dbContext.SaveChanges();
      }

      if (quit)
      {
        ChatService.SendMessage(player, $"~y~[JOB]~s~ Du hast deinen Job ~o~{this.Name}~s~ beendet.");
      }

      

      JobStop?.Invoke(player);
    }

    public List<JobVehicle> GetJobVehicles()
    {
      using (var dbContext = new DatabaseContext())
      {
        return dbContext.JobVehicles.Where(j => j.JobId == Id).ToList();
      }
    }

    public static List<Player> GetPlayerInJob() => jobPlayer;

    public List<Player> GetUsersInJob() => _inJob;
  }
}
