--- этот модуль определеяет рабоут виджета отрисоывающего время, часы и эффекты часов
time_widget = {}

__inherite(time_widget, null_lua_widget_handler())

function time_widget.__CreateInstance()
    return "time_widget"
end

-- поззиция в которую прилетает временной бонус
time_widget.time_bonus_target_pos = sf.misc.FloatVector(150, 300)

-- текущее время
time_widget._time = 0


time_widget._blink_avatar_cahnged = nil -- флаг того что загрустили аватар
time_widget._blink_avatar_cahnged_index = nil -- цвет вермени в конце которого будет грусть

-- id текстур, которые реализуют диски на часах
time_widget._clock_images = {
	[0] = "screens_game_clock_green",
	[1] = "screens_game_clock_yellow",
	[2] = "screens_game_clock_blue"
} 

function time_widget.InitAvatartWarningIndex(_index)
	time_widget._blink_avatar_cahnged_index = _index
end

function time_widget.SetAllowTimeWarning(_value)
	time_widget._allow_time_warning = _value
end

function time_widget.Load(_this, _info, _templates)
	time_widget._allow_time_warning = true
	time_widget._blink_avatar_cahnged = nil
	time_widget._blink_avatar_cahnged_index = nil

	time_widget._text_font = sf.core.g_Application.GetResourceManager().GetFont("test_font")		
	
	time_widget._time_label = get_child_widget(_this, "time_label", sf.gui.CLabelWidget, "ошибка" )
	time_widget._time_limit_label = get_child_widget(_this, "time_limit_label", sf.gui.CLabelWidget, "ошибка" )

	time_widget._boundary_texture = sf.core.g_Application.GetResourceManager().GetTexture("screens_game_clock_shadow")
	
	local clock_options = g_App.GetSettings().GetChild("Constants", false).GetChild("clock_options", false)
	time_widget._blinking_time = tonumber(clock_options.GetValue("blinking_time").c_str())
	time_widget._blinking_count = tonumber(clock_options.GetValue("blinking_count").c_str())
end

--- первоначальная инициализация
function time_widget.Init(_level)
	local settings = game_window.game_field.GetGameplaySettings()
	--- загрузка из уровня информации о временах и инициализируем изображения дисков
	time_widget._times = {}
	for i = 0, _level.PrizeTimesCount-1  do
		time_widget._times[i] = {}
		
		time_widget._times[i].time_limit = settings.GetPrizeTimeInfo(i).Time
		--- заранее формируем строку со временем лимита времени 
		if i == 2 then
			time_widget._times[i].time_str = ""
		else
			time_widget._times[i].time_str = TimeToString(time_widget._times[i].time_limit)
		end
		--- находим изображения дисков
		local texture = sf.core.g_Application.GetResourceManager().GetTexture(time_widget._clock_images[i])
		local texture_center = sf.core.g_Application.GetResourceManager().GetTexture(time_widget._clock_images[i].."_center")
		local texture_back = sf.core.g_Application.GetResourceManager().GetTexture(time_widget._clock_images[i].."_back")
		time_widget._times[i].texture = texture
		time_widget._times[i].texture_center = texture_center
		time_widget._times[i].texture_back = texture_back
	end
	--- первоначально инициализируем виджеты 
	time_widget._time = game_window.game_field.GetGameTime()
	
	time_widget._InitLabels(true)
end

--- инициализация виджетов текущего времени и ограничения по времени
function time_widget._InitLabels()
	time_widget._time_label.SetText(TimeToString(time_widget._time))
	local current_time_state = game_window.game_field.GetPrizeIndex()
	time_widget._time_limit_label.SetText(time_widget._times[current_time_state].time_str)
end

function time_widget.DoUpdate(_this)
	return false
end

function time_widget.DoDraw(_this, _renderer)
	time_widget._time = game_window.game_field.GetGameTime()

	time_widget._InitLabels()

	local idx = game_window.game_field.GetPrizeIndex()
		
	if idx < 2 then
		_renderer.RenderTexture(time_widget._times[idx+1].texture.GetTexture(0), 0, 0, 
			sf.graphics.Color(255,255,255,255))
		
		local current_time = time_widget._time
		local time_limit = time_widget._times[idx].time_limit
		if idx == 1 then
			time_limit = time_limit - time_widget._times[idx-1].time_limit
			current_time = current_time - time_widget._times[idx-1].time_limit
		end
		
		if current_time < 0.001 then
			_renderer.RenderTexture(time_widget._times[idx].texture.GetTexture(0), 0, 0, sf.graphics.Color(255,255,255,255))
		else
			local begin_rad = (current_time / time_limit) * 2 * math.pi
			local end_rad = 2 * math.pi
			s11.misc.RenderTextureSector(_renderer, time_widget._times[idx].texture.GetTexture(0), 
				time_widget._boundary_texture.GetTexture(0), begin_rad, end_rad)
			_renderer.PushState()
			_renderer.SetColor(sf.graphics.Color(90, 255, 255,255)*_renderer.GetColor())
			s11.misc.RenderTextureSector(_renderer, time_widget._times[idx].texture.GetTexture(0), 
				nil, begin_rad -0.015, end_rad)
			_renderer.PopState()
		end
		
		_renderer.RenderTexture(time_widget._times[idx].texture_center.GetTexture(0), 56, 59, 
			sf.graphics.Color(255,255,255,255))
			
		_renderer.RenderTexture(time_widget._times[idx].texture_back.GetTexture(0), 37, 131, 
			sf.graphics.Color(255,255,255,255))
		
		local time_rest = time_limit - current_time
		if time_rest <= time_widget._blinking_time then
			if time_widget._allow_time_warning == true then
				__sound("time_warning")
			end
			if time_widget._blink_avatar_cahnged == nil and time_widget._blink_avatar_cahnged_index == idx then
				time_widget._blink_avatar_cahnged = true
				avatar_widget.ChangeMood("time_limit")
			end
			
			local k = math.cos((2 * math.pi * time_widget._blinking_count + math.pi) * (time_rest / time_widget._blinking_time)) + 1.0
			local alpha = 127.5 * k
			
			_renderer.PushState()
			
			_renderer.SetBlendMode(sf.graphics.CRenderer.BlendAdditive)
			
			_renderer.RenderTexture(time_widget._times[idx].texture_center.GetTexture(0), 56, 59, 
			sf.graphics.Color(alpha,255,255,255))
			
			_renderer.RenderTexture(time_widget._times[idx].texture_back.GetTexture(0), 37, 131, 
				sf.graphics.Color(alpha,255,255,255))
				
			_renderer.PopState()
		else
			time_widget._blink_avatar_cahnged = nil
		end
	else
		_renderer.RenderTexture(time_widget._times[idx].texture.GetTexture(0), 0, 0, 
		sf.graphics.Color(255,255,255,255))
	end
	
    return false
end

function time_widget.OnMouseMove(_this, _pos, _state, _broadcast)
    return false
end

function time_widget.OnMouseUp(_this, _pos, _button, _state, _broadcast)
    return false
end

function time_widget.OnMouseDown(_this, _pos, _button, _state, _broadcast)
    return false
end

function time_widget.OnDoubleClick(_this, _pos, _state, _broadcast)
    return true
end