#include "../../config/events.lua"
#include "../../script/helpers/entity.lua"

local locs
local levelcase = {
    lobby_2_1a = 1,
    lobby_2_1 = 2,
    lobby_2_1b = 3,
    lobby_2_2a = 4,
    lobby_2_2b = 5,
    lobby_2_2c = 6,
    lobby_3_0 = 7,
}
function init()
    locs = FindLocations()
    RegisterListenerTo(EVENTS.MAIN_FIRST_TICK, "FirstTick")
end

function FirstTick()
    UnregisterListener(EVENTS.MAIN_FIRST_TICK, "FirstTick")

    local levelid = GetString("game.levelid")
    if levelid == "lobby_4" then
        local nosnows = FindBodies("nosnow", true)
        local baab = -1
        for i = 1, #nosnows do
            local body = nosnows[i]
            local veh = GetBodyVehicle(body)
            if veh > 0 and HasTag(body, "autobreak") then
                baab = veh
                break
            end
        end
        SetInt("level.carlift_obstacle", baab)
        Trigger()
        return
    end
    local matching = levelcase[levelid]
    if not matching or GetBool("savegame.mod.lobby_spawns." .. matching) then
        Trigger()
        return
    end

    if matching == 7 then
        SetBool("savegame.mod.lobby_spawns", true)
    elseif matching == 2 and GetInt("level.stars") < 31 then
        Trigger()
        return
    end

    SetBool("savegame.mod.lobby_spawns." .. matching, true)
    SetInt("level.lobby_spawn", matching)
    if matching == 1 then
        SetInt("level.carlift_obstacle", -1)
    end

    local loc = locs[matching]
    if matching == 1 then
        local saved_ladoga = GetString("savegame.mod.available_vehicles.ladoga.save")
        SetString("savegame.mod.available_vehicles.garage_vehicle", saved_ladoga)
    end
    if loc then
        SetPlayerTransform(GetLocationTransform(loc))
        if HasTag(loc, "sit") then
            TriggerEvent(EVENTS.UPDATE_STATE, "sit")
        end
    end
    Trigger()
end

function Trigger()
    TriggerEvent(EVENTS.SPAWN_SET, "player_spawn")
    cEntity:EnqueueDeletion()
end
