using System;
using System.Collections.Generic;
using System.Text;
using GTANetworkAPI;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Server.Job;
using ReallifeGamemode.Server.Managers;
using ReallifeGamemode.Server.Util;

namespace ReallifeGamemode.Server.Extensions
{
  public static class ServerVehicleExtensions
  {
    public static JobBase GetJob(this JobVehicle vehicle)
    {
      return JobManager.GetJob(vehicle.JobId);
    }

    public static Vehicle GetVehicle(this ServerVehicle veh) => VehicleManager.GetVehicleFromServerVehicle(veh);

    public static Vehicle Spawn(this ServerVehicle veh, Vehicle currentVeh = null)
    {
      if (currentVeh != null) VehicleManager.DeleteVehicle(currentVeh);
      Vector3 position = veh.Position;
      uint model = (uint)veh.Model;
      float heading = veh.Heading;
      int c1 = veh.PrimaryColor;
      int c2 = veh.SecondaryColor;
      Vehicle newVeh = NAPI.Vehicle.CreateVehicle(model, position, heading, c1, c2, "", 255, false, false);
      veh.Livery = veh.Livery;     
      VehicleStreaming.SetEngineState(newVeh, false);
      VehicleStreaming.SetLockStatus(newVeh, veh.Locked);
      VehicleManager.AddVehicle(veh, newVeh);
      newVeh.Rotation = new Vector3(0,0,heading);

      newVeh.SetSharedData("drivenDistance", veh.DistanceDriven);

      string numberplate = $"{veh.Id}";

      if (veh is FactionVehicle fV)
      {
        numberplate = $"F{fV.FactionId} " + numberplate;
      }

      if (veh is UserVehicle uV)
      {
        numberplate = $"U{uV.UserId} " + numberplate;
      }

      if (veh is ShopVehicle sV)
      {
        numberplate = "Shop";
        VehicleStreaming.SetLockStatus(newVeh, false);
        TextLabel label = NAPI.TextLabel.CreateTextLabel("SHOPVEHICLE\n" + "~g~" + sV.Price.ToMoneyString(),
            veh.Position.Add(new Vector3(0, 0, 1.3)), 20.0f, 1f, 1, new Color(255, 255, 255));

        newVeh.SetSharedData("shopVehicleTextLabel", label.Handle.Value);
      }

      if (veh is GroupVehicle gV)
      {
        numberplate = $"G{gV.GroupId} " + numberplate;
      }

      if (veh is JobVehicle jV)
      {
        numberplate = $"J{jV.JobId} " + numberplate;
      }
      NAPI.Vehicle.SetVehicleNumberPlate(newVeh, numberplate);
      veh.NumberPlate = numberplate;

      return newVeh;
    }
  }
}
