local M = {}

local running = true
local scenario = nil
local player = nil
local helper = require('scenario/scenariohelper')

local function reset()
    running = false
	helper.queueLuaCommandByName('scenario_player0', 'bullettime.set(1)')
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()

    helper.trackVehicle('aiCar1', 'aiCarA')
	helper.trackVehicle('aiCar2', 'aiCarB')
	helper.trackVehicle('aiCar3', 'aiCarC')
	helper.trackVehicle('clone1', 'bridge')
	
	local car1 = scenetree.findObject('aiCar1')
	local car2 = scenetree.findObject('aiCar2')
	local car3 = scenetree.findObject('aiCar3')
	
	player = scenetree.findObject('scenario_player0')
	
	TorqueScript.eval('clone1.rotation = \"0 0 1 90\";')
	TorqueScript.eval('clone1.rotation = \"1 0 0 0\";')
	
	scenario = scenario_scenarios.getScenario()
	if not scenario then return end
	
	local aiData1 = jsonReadFile('levels/sadlerGorge/scenarios/motorcade_1.json')
	local aiData2 = jsonReadFile('levels/sadlerGorge/scenarios/motorcade_2.json')
	local aiData3 = jsonReadFile('levels/sadlerGorge/scenarios/motorcade_3.json')
	car1:queueLuaCommand("ai.startFollowing("..serialize(aiData1.recording)..")")
	car2:queueLuaCommand("ai.startFollowing("..serialize(aiData2.recording)..")")
	car3:queueLuaCommand("ai.startFollowing("..serialize(aiData3.recording)..")")

    running = true
end

local function onRaceTick(raceTickTime)
    if not running then
        return
    end
	
	local aiCarAData = map.objects[map.objectNames['aiCarA']]
	local aiCarBData = map.objects[map.objectNames['aiCarB']]
	local aiCarCData = map.objects[map.objectNames['aiCarC']]
	local bridgeData = map.objects[map.objectNames['bridge']]
	
	local playerPos = player:getPosition()
	local playerX = playerPos.x
	
	if playerX <= 25 then
		helper.queueLuaCommandByName('scenario_player0', 'bullettime.set(2)')
	end
	
	if bridgeData.damage > 125 then
		helper.setAiMode('aiCar1', 'stop')
		helper.setAiMode('aiCar2', 'stop')
		helper.setAiMode('aiCar3', 'stop')
	end
	
    if scenario.timer > 40 then
		targetDamage = aiCarAData.damage + aiCarBData.damage + aiCarCData.damage
		if targetDamage >= 18000 then
			success({msg = "The All-Seeing Eye didn't call that one, did it?"})
		else
			fail("You... you missed. HOW?")
		end
    end
end

local function onScenarioChange(sc)
    scenario = sc
end

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

return M