local M = {}

local running = true
local scenario = nil
local player = nil
local car1 = nil
local car2 = nil
local slomo = 0
local rollover = 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
	rollover = 0
end

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

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

local function onRaceStart()
    reset()
	
	player = scenetree.findObject('scenario_player0')
	car1 = scenetree.findObject('aiCar1')
	car2 = scenetree.findObject('aiCar2')
	
	local aiData1 = jsonReadFile('levels/sadlerGorge/scenarios/gorge_film_victim_a.json')
	local aiData2 = jsonReadFile('levels/sadlerGorge/scenarios/gorge_film_victim_b.json')
	car1:queueLuaCommand("ai.startFollowing("..serialize(aiData1.recording)..")")
	car2:queueLuaCommand("ai.startFollowing("..serialize(aiData2.recording)..")")
	
    running = true
end

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

local function onRaceTick(raceTickTime)
    if not running then
        return
    end
	
	local playerPos = player:getPosition()
	local aiCar1Data = map.objects[map.objectNames['aiCar1']]
	local aiCar2Data = map.objects[map.objectNames['aiCar2']]
	local car1Pos = car1:getPosition()
	local car2Pos = car2:getPosition()
	
	if aiCar1Data.damage > 1500 then
		helper.setAiMode('aiCar1', 'stop')
	end
	
	if aiCar2Data.damage > 500 or car2Pos.y < -5 then
		helper.setAiMode('aiCar2', 'stop')
	end
	
	if rollover == 0 then
		if slomo == 0 then
			if playerPos.y > -50 then
				helper.queueLuaCommandByName('scenario_player0', 'bullettime.set(2)')
				slomo = 1
			elseif scenario.timer > 19 then
				fail("You have to drive to the bridge!")
			end
		elseif slomo == 1 and playerPos.y > -28 then
			fail("Cut! You have to hit the ramp.")
		end
	elseif rollover == 1 and slomo == 1 and scenario.timer > 21 then
		slomo = 2
		helper.queueLuaCommandByName('scenario_player0', 'bullettime.set(1)')
	end
	
	if scenario.timer > 27 and destructionCheck == 0 then
		if playerPos.z < 190 or car1Pos.z < 190 or car2Pos.z < 190 then
			fail("Cut! All three vehicles need to remain on the bridge.")
		elseif playerPos.y > 20 or car1Pos.y < -20 then
				fail("Cut! All three vehicles need to remain near the center of the bridge. Clean up the set, we'll reshoot tomorrow.")
		else
			destructionCheck = 1
			helper.flashUiMessage('Charges armed! Fire in the Hole!', 1.5)
		end
	elseif scenario.timer > 30 and destructionCheck == 1 then
		destructionCheck = 2
		helper.queueLuaCommandByName('scenario_player0', 'bullettime.set(2)')

		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
	
	if scenario.timer > 50 and running == true then
		running = false
		if playerPos.z > 185 then
			success({msg = "Your car was supposed to fall too... Erm, we'll fix it in post."})
		else
			success({msg = "That's a wrap! Outstanding!"})
		end
	end
end

local function onScenarioChange(sc)
    scenario = sc
end

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

return M