local M = {}

local running = true
local scenario = nil
local player = nil
local car1 = nil
local car2 = nil
local slomo = 0
local jump = 0
local destructionCheck = 0

local helper = require('scenario/scenariohelper')

local function reset()
    running = false
	helper.queueLuaCommandByName('scenario_player0', 'bullettime.set(1)')
	slomo = 0
	destructionCheck = 0
	jump = 0
	
	helper.breakBreakGroup("clone1", "deckSupportA")
	helper.breakBreakGroup("clone1", "deckSupportB")
	helper.breakBreakGroup("clone1", "deckSupportC")
	helper.breakBreakGroup("clone1", "deckSupportD")
	helper.breakBreakGroup("clone1", "deckSupportN")
	helper.breakBreakGroup("clone1", "deckSupportO")
	helper.breakBreakGroup("clone1", "towerA")
	helper.breakBreakGroup("clone1", "towerB")
	helper.breakBreakGroup("clone1", "towerC")
	helper.breakBreakGroup("clone1", "towerD")
	helper.breakBreakGroup("clone1", "towerE")
end

local function fail(reason)
    scenario_scenarios.finish({failed = reason})
    reset()
end

local function success(result)
    scenario_scenarios.finish(result)
    reset()
end

local function onCountdownStarted()
	player = scenetree.findObject('scenario_player0')
	car1 = scenetree.findObject('aiCar1')
	car2 = scenetree.findObject('aiCar2')
	
	local aiData = jsonReadFile('levels/sadlerGorge/scenarios/gorge_film_victim_c.json')
	car1:queueLuaCommand("ai.startFollowing("..serialize(aiData.recording)..")")
end

local function onRaceStart()
    reset()
    running = true
end

local function onBeamNGTrigger(data)
	if data.subjectName == 'scenario_player0' then
		jump = 1
	end
end

local function onRaceTick(raceTickTime)
    if not running then
        return
    end
	
	local playerPos = player:getPosition()
	local playerData = map.objects[map.objectNames['scenario_player0']]
	local aiCar1Data = map.objects[map.objectNames['aiCar1']]
	local car1Pos = car1:getPosition()
	local sheriffDistance = math.abs((car1Pos - playerPos):len())
	
	if scenario.timer < 5 then
		car2:queueLuaCommand("input.event('tilt',1,0)")
		car2:queueLuaCommand("input.event('extend',1,0)")
		helper.queueLuaCommandByName('aiCar1', 'electrics.set_lightbar_signal(2)')
		helper.queueLuaCommandByName('scenario_player0', 'electrics.set_lightbar_signal(2)')
	end
	
	if jump == 0 then
		if car1Pos.y > 55 then
			if sheriffDistance > 30 then
				fail("Cut! You need to keep up with the sheriff!")
			elseif aiCar1Data.damage > 100 then
				fail("Cut! Don't wreck the sheriff!")
			end
		else
			jump = 1
			helper.queueLuaCommandByName('scenario_player0', 'bullettime.set(4)')
		end
	elseif jump == 1 then
		if aiCar1Data.damage > 1500 then
			helper.queueLuaCommandByName('aiCar1', 'electrics.set_lightbar_signal(0)')
		end
		
		if playerPos.z < 190 then
			fail("Oh, god. I need recovery on-site NOW!")
		elseif playerPos.y < -22 then
			helper.queueLuaCommandByName('scenario_player0', 'bullettime.set(1)')
			helper.queueLuaCommandByName('scenario_player0', 'electrics.set_lightbar_signal(1)')
			
			if playerData.vel:length() < 1 then
				jump = scenario.timer
			end
		else
			if scenario.timer > 30 then
				fail("You've gotta take the jump!")
			end
		end
	else
		if playerPos.z < 160 then
			fail("Oh, god. I need recovery on-site NOW!")
		elseif scenario.timer >= (jump + 3) then
			success({msg = "Cut. Print. Pop the champagne. Good job, crew!"})
		end
	end
end

local function onScenarioChange(sc)
    scenario = sc
end

M.onRaceStart = onRaceStart
M.onRaceTick = onRaceTick
M.onScenarioChange = onScenarioChange
M.onBeamNGTrigger = onBeamNGTrigger
M.onCountdownStarted = onCountdownStarted

return M