local M = {}

local running = true
local scenario = nil
local result = nil

local helper = require('scenario/scenariohelper')

local function reset()
    running = false
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('rock', 'rock')
	helper.trackVehicle('clone1', 'bridge')
	helper.trackVehicle('scenario_player0', 'player')

	scenario = scenario_scenarios.getScenario()
	if not scenario then return end
	
	TorqueScript.eval('clone1.rotation = \"0 0 1 90\";')
	TorqueScript.eval('clone1.rotation = \"1 0 0 0\";')
	TorqueScript.eval('rock.position = \"0 0 250\";')

	running = true
end

local function onRaceTick(raceTickTime)
    if not running then
        return
    end
	
	local rockData = map.objects[map.objectNames['rock']]
	local bridgeData = map.objects[map.objectNames['bridge']]
	local playerData = map.objects[map.objectNames['player']]
	
	if not aiCarAData then
        return
    end
	
	local rock = scenetree.findObject('rock')
	local rockPos = rock:getPosition()
	if scenario.timer > 4 and scenario.timer < 4.4 then
		if rockPos.z > 195 and bridgeData.damage < 20000 then
			fail("Clever, but the rock MUST hit the bridge.")
		end
	end
	print(bridgeData.damage)
	
	if scenario.timer > 2 and scenario.timer < 2.1 then
		helper.flashUiMessage('Press F8 to enter freecam mode.', 4)
	elseif scenario.timer > 6 and scenario.timer < 6.1 then
		helper.flashUiMessage('Use the node grabber to repair the bridge.', 4)
	end
end

local function onScenarioChange(sc)
    scenario = sc
end

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

return M