:NAME kill_timer

:VAR float32	time_left
:VAR boolean	started

:PARAM float32 unused

:CONFIG float32 initial_time


-- ------------------- constants ------------------- 

k_default_time= 10


-- ------------------- initialization ------------------- 

function var_initialize(v)
	v.time_left= 0
	v.started= false
end

function param_initialize(p)
end

function config_initialize(c)
	c.initial_time= k_default_time
end

-- ------------------- component ------------------- 

function timer_expire(object)
	local game_hud= world_state_get().global_script("game_hud")
	game_hud.loss_pending= true
end

function timer_text_update(object, time)

	local mins= math.modf(time/60)
	local seconds= time - (mins*60)
	
	seconds= math.ceil(seconds)
	
	local text= ""..mins..":"
	if (seconds < 10) then
		text= text.."0"
	end
	text= text..seconds
	
	local text_component= object.text_get()
	if (text_component) then
		text_component.text_set(text)
	end

end


function attach(object)
	var.time_left= config.initial_time
	timer_text_update(object, var.time_left)
end

function update(object)

	-- update time
	if (var.started) then
		if (var.time_left > 0) then
		
			local ws= world_state_get()
			local dt= ws.time.delta_t()
			
			var.time_left = var.time_left - dt
			
			if (var.time_left <= 0) then
				var.time_left= 0
				timer_expire()
			end
			
			timer_text_update(object, var.time_left)
				
		end
	else
		local ws= world_state_get()
		local game_hud= ws.global_script("game_hud")
		if (game_hud and game_hud.first_move_time >= 0) then
			var.started= true
			
			local tween= object.tween_get()
			if (tween) then
				tween.stop_all()
				tween.play_animation("started")
			end
		end
	end
end

component_register(attach, update, nil, nil)
