achievements = achievements or {}

achievements.params = 
{
	back_image_completed = "screens_game_achievment_completed", -- изображение подложки полученной ачивки
	back_image_uncompleted = "screens_game_achievment", -- изображение подложки промежуточной ачивки
	back_rect  = { x = 340, y = 570, x2 = 1002, y2 = 750 }, -- расположение подложки
	icon_pos = { x = 400, y = 620 }, -- позиция левого верхнего угла иконки ачивмента
	font = "mpc_semibold_30_green",  -- шрифт
	info_pos = { x = 525, y = 620}, -- позиция описания/названия ачивмента
	progress_image = "achievements_progress02",
	progress_image_frame = "achievements_progress02_frame",
	progress_pos = { x = 550, y = 660 }, -- позиция прогресса ачивмента
    score_pos = { x = 899, y = 627}, -- позиция очков
	scores_font = "na_gradient_44",  -- шрифт
	view_time = 3000, -- время в мс, сколько будет отображаться окошко с ачивкой
	clip_completed = "achievement_gamefield02",
	clip_uncompleted = "achievement_gamefield01"
}

achievements.templates = 
{
	window_center = {pos = sf.misc.FloatVector(181, 570)},
	hog_stat = {pos = sf.misc.FloatVector(32, 545)}
}

function achievements.IsCompleted(_achievement)
	local profile = s11.g_ProfileManager.Instance().GetCurrentProfile()
	__assert(profile)
		
	local achs = s11.g_Achievements.Instance().GetProfileAchievements(profile)

	if achs.IsCompleted(_achievement) ~= 0 then return true end
	return false
end

function achievements.RefreshAchievement(_achievement, _new_progress)
	
	local profile = s11.g_ProfileManager.Instance().GetCurrentProfile()
	__assert(profile)
		
	local achs = s11.g_Achievements.Instance().GetProfileAchievements(profile)

	if achs.IsCompleted(_achievement) ~= 0 then return false end
	
	local old_progress = achs.GetProgress(_achievement) or 0
	if old_progress >= _new_progress then return false end
	return achievements._AddAchProgress(achs, _achievement, _new_progress - old_progress)
end

function achievements.GetAchievement(_achievement)
	
	local profile = s11.g_ProfileManager.Instance().GetCurrentProfile()
	__assert(profile)
		
	local achs = s11.g_Achievements.Instance().GetProfileAchievements(profile)

	if achs.IsCompleted(_achievement) ~= 0 then return false end
	return achievements._AddAchProgress(achs, _achievement, 1)
end

function achievements._AddAchProgress(_achs, _achievement, _progress)
	_achs.AddProgress(_achievement, _progress)
	local cur_progress = _achs.GetProgress(_achievement)
	local ach_settings = s11.g_Achievements.Instance().GetAchievementSettings(_achievement)
	local completed = cur_progress == ach_settings.MaxProgress 
	local show_progress = (cur_progress == 1 and ach_settings.MaxProgress==1) or (ach_settings.MaxProgress > 1 and cur_progress % ach_settings.ShowProgressStep == 0)
	if completed or show_progress then
		__sound("achievement_take")
		achievements._ShowPopup(_achievement, _achs.GetProgress(_achievement), completed) 
		return true
	end
	return false
end

function achievements._ShowPopup(_achievement, _progress, _completed)
	if _completed then
		--__message("completed")
	end
	
	achievements.completed = _completed
	
	local settings = s11.g_Achievements.Instance().GetAchievementSettings(_achievement)

	achievements.icon = sf.core.g_Application.GetResourceManager().GetTexture(settings.Image)
	__assert(achievements.icon, "ACHIEVEMENTS: не найдена иконка ачивмента '"..tostring(settings.Image).."'!")
	
	-- если макс. прогресс больше 1, то надо отобразить текущий прогресс
	achievements.progress = nil
	if settings.MaxProgress > 1 then
		achievements.progress = _progress
		achievements.max_progress = settings.MaxProgress
	end
	
	local template = achievements.templates[settings.ShowTemplate.c_str()]
	if template then
		local top_left = achievements.params.back_rect
		achievements.this.SetOffset(template.pos.X - top_left.x, template.pos.Y - top_left.y)
	end
    achievements.score = settings.Score
	achievements.title = settings.Title
	achievements.timer.Get().SetTime(0)
	achievements.clip_completed.SetTime(0)
	achievements.clip_uncompleted.SetTime(0)
		
	achievements.visible = true
end

function achievements.DoDraw(_this, _renderer)
	if not achievements.visible then return false end
	
	-- отрисовываем подложку
	local dest = sf.misc.FloatRect(achievements.params.back_rect.x, achievements.params.back_rect.y, 0, 0)
	dest.Width = achievements.params.back_rect.x2 - dest.X
	dest.Height = achievements.params.back_rect.y2 - dest.Y
	
	if achievements.completed then
		_renderer.RenderTextureBox(achievements.back_image_completed.GetTexture(0), dest, 
			sf.misc.IntRect(0, 0, achievements.back_image_completed.GetWidth(), achievements.back_image_completed.GetHeight()), sf.graphics.Color(255, 255, 255, 255)) 
	else
		_renderer.RenderTextureBox(achievements.back_image_uncompleted.GetTexture(0), dest, 
			sf.misc.IntRect(0, 0, achievements.back_image_uncompleted.GetWidth(), achievements.back_image_uncompleted.GetHeight()), sf.graphics.Color(255, 255, 255, 255)) 
	end
	
	-- отрисовываем иконку ачивмента
	_renderer.RenderTexture(achievements.icon.GetTexture(0), 
		achievements.params.icon_pos.x, achievements.params.icon_pos.y, sf.graphics.Color(255, 255, 255, 255))
		
	--  название ачивмента
	_renderer.RenderString(achievements.font, achievements.title, achievements.params.info_pos.x, achievements.params.info_pos.y, -1, -1, 1, 
		sf.graphics.Color(255, 255, 255, 255), sf.graphics.Color(0, 255, 255, 255))
		
	-- прогресс
	if achievements.progress then
		_renderer.RenderTexture(achievements.progress_image_frame.GetTexture(0), achievements.params.progress_pos.x, 
			achievements.params.progress_pos.y, sf.graphics.Color(255, 255, 255, 255))
		
		local k = achievements.progress / achievements.max_progress	
		local rect = sf.misc.IntRect(achievements.progress_image.GetTexture(0).GetRect())		
		local dest_rect = sf.misc.FloatRect(achievements.params.progress_pos.x, achievements.params.progress_pos.y, 
			rect.Width * k, rect.Height)			
		local src_rect = sf.misc.IntRect(0, 0, rect.Width * k, rect.Height)
		
		_renderer.RenderTexture(achievements.progress_image.GetTexture(0), dest_rect, src_rect, 
			sf.graphics.Color(255, 255, 255, 255))		
	end
   
    -- очки отрисовываем, только если ачвмент выполнен полностью
	if achievements.completed then
		_renderer.RenderString(achievements.scores_font, tostring(achievements.score), 
			achievements.params.score_pos.x, achievements.params.score_pos.y, -1, -1, 1, 
			sf.graphics.Color(255, 255, 255, 255), sf.graphics.Color(0, 255, 255, 255))
	end
	
	-- клип
	if achievements.completed then
		achievements.clip_completed.Draw(_renderer)
	else
		achievements.clip_uncompleted.Draw(_renderer)
	end
	
	if achievements.timer.Get().GetTime() >= achievements.params.view_time then
		achievements.visible = false
	end
	
	return false
end

function achievements.DoUpdate(_this)
	if achievements.visible then
		if achievements.completed then
			achievements.clip_completed.Update()
		else
			achievements.clip_uncompleted.Update()
		end
	end
	return false
end

function achievements.OnMouseDown(_this, _pos, _button, _state, _broadcast)
	if not _broadcast then
		local rect = achievements.params.back_rect
		if _pos.X >= rect.x and _pos.X <= rect.x2 and _pos.Y >= rect.y and _pos.Y <= rect.y2 then
			achievements.visible = false
		end
	end
	return false
end

function achievements.Load(_this)
	achievements.this = _this
	
	achievements.font = sf.core.g_Application.GetResourceManager().GetFont(achievements.params.font)
	__assert(achievements.font, "ACHIEVEMENTS: шрифт '"..achievements.params.font.."' не найден!")
	
	achievements.scores_font = sf.core.g_Application.GetResourceManager().GetFont(achievements.params.scores_font)
	__assert(achievements.scores_font, "ACHIEVEMENTS: шрифт '"..achievements.params.scores_font.."' не найден!")
	
	achievements.back_image_completed = sf.core.g_Application.GetResourceManager().GetTexture(achievements.params.back_image_completed)
	__assert(achievements.back_image_completed, "ACHIEVEMENTS: изображение '"..achievements.params.back_image_completed.."' не найдено!")
	
	achievements.back_image_uncompleted = sf.core.g_Application.GetResourceManager().GetTexture(achievements.params.back_image_uncompleted)
	__assert(achievements.back_image_uncompleted, "ACHIEVEMENTS: изображение '"..achievements.params.back_image_uncompleted.."' не найдено!")
	
	achievements.progress_image = sf.core.g_Application.GetResourceManager().GetTexture(achievements.params.progress_image)
	__assert(achievements.progress_image, "ACHIEVEMENTS: изображение '"..achievements.params.progress_image.."' не найдено!")
	
	achievements.progress_image_frame = sf.core.g_Application.GetResourceManager().GetTexture(achievements.params.progress_image_frame)
	__assert(achievements.progress_image_frame, "ACHIEVEMENTS: изображение '"..achievements.params.progress_image_frame.."' не найдено!")
	
	achievements.clip_completed = sf.misc.anim.CClip()
	achievements.clip_completed.Load(achievements.params.clip_completed, true)
	
	achievements.clip_uncompleted = sf.misc.anim.CClip()
	achievements.clip_uncompleted.Load(achievements.params.clip_uncompleted, true)
	
	local clip_x = achievements.params.back_rect.x + (achievements.params.back_rect.x2 - achievements.params.back_rect.x) / 2
	local clip_y = achievements.params.back_rect.y + (achievements.params.back_rect.y2 - achievements.params.back_rect.y) / 2
	
	achievements.clip_completed.SetPos(sf.misc.FloatVector(clip_x, clip_y))
	achievements.clip_uncompleted.SetPos(sf.misc.FloatVector(clip_x, clip_y))
	
	achievements.visible = false
	achievements.timer = __create_timer()
end

function achievements.__CreateInstance()
	return "achievements"
end

__inherite( achievements, null_lua_widget_handler() )