--[[Игра "Проявление картинки"]]

reveal_image = {}

local self = reveal_image

self.params = {
	piece_id = "piece", -- id картинки с частью рисунка (dsfrontend)
	speed = 7, -- скорость проявления картинок
	min_alpha = 100, -- минимальное значение альфы, при котором картинка считается проявленной
	neighbour_alpha = 5, -- на сколько увеличивается альфа у соседей
	cursor = "gui_cursors_shawl", -- id  картинки для курсора (не из dsfrontend, а полное название из resources.xml)
	cursor_height = 220, -- высота курсора
	cursor_width = 84, -- ширина курсора
	clip = "", -- id клипа с эффектом пыли от угля
	sound_id = "mini_game_mini_game_reveal_image_01", -- звук протирания тряпочкой
	sound_fade_time = 800, -- мс, время затухания звука
	positions = { -- позиции кусков проявляемой картинки и номера соседних кусков
		-- если есть should_be_visible = true, значит, этот кусочек должен быть отчищен. Если этого для кусочка нету, значит, неважно, будет ли он очищен
		{X = 299, Y = 147, neighbour = {2, 6} }, -- piece01
		{X = 338, Y = 66, neighbour = {1, 7, 3}}, -- piece02
		{X = 438, Y = 61, neighbour = {2, 8, 4}}, -- piece03
		{X = 538, Y = 74, neighbour = {3, 9, 5}}, -- piece04
		{X = 638, Y = 152, neighbour = {4, 10}}, -- piece05  
		
		{X = 238, Y = 161, neighbour = {1, 7, 11}, should_be_visible = true}, -- piece06 
		{X = 338, Y = 161, neighbour = {6, 2, 8, 12}, should_be_visible = true}, -- piece07
		{X = 438, Y = 161, neighbour = {7, 3, 9, 13}, should_be_visible = true}, -- piece08
		{X = 538, Y = 161, neighbour = {8, 4, 10, 14}, should_be_visible = true}, -- piece09 
		{X = 638, Y = 161, neighbour = {9, 5, 15}, should_be_visible = true}, -- piece010
		
		{X = 249, Y = 261, neighbour = {6, 16, 12}}, -- piece011
		{X = 338, Y = 261, neighbour = {11, 7, 13, 17}, should_be_visible = true}, -- piece012
		{X = 438, Y = 261, neighbour = {12, 8, 14, 18}, should_be_visible = true}, -- piece013
		{X = 538, Y = 261, neighbour = {13, 9, 15, 19}, should_be_visible = true}, -- piece014
		{X = 638, Y = 261, neighbour = {14, 10, 20}, should_be_visible = true}, -- piece015
		
		{X = 261, Y = 361, neighbour = {11, 17, 21}}, -- piece016
		{X = 338, Y = 361, neighbour = {16, 12, 18, 22}, should_be_visible = true}, -- piece017
		{X = 438, Y = 361, neighbour = {17, 13, 19, 23}, should_be_visible = true},  -- piece018
		{X = 538, Y = 361, neighbour = {18, 14, 20, 24}, should_be_visible = true},  -- piece019
		{X = 638, Y = 361, neighbour = {19, 15, 25}},  -- piece020
		
		{X = 273, Y = 461, neighbour = {16, 22, 26}},  -- piece021
		{X = 338, Y = 461, neighbour = {21, 17, 23, 27}, should_be_visible = true},  -- piece022
		{X = 438, Y = 461, neighbour = {22, 18, 24, 28}, should_be_visible = true},  -- piece023
		{X = 538, Y = 461, neighbour = {23, 19, 25, 29}, should_be_visible = true},  -- piece024
		{X = 638, Y = 461, neighbour = {24, 20, 30}},  -- piece025
		
		{X = 284, Y = 561, neighbour = {21, 27}},  -- piece026
		{X = 338, Y = 561, neighbour = {26, 22, 28}},  -- piece027
		{X = 438, Y = 561, neighbour = {27, 23, 29}},  -- piece028
		{X = 538, Y = 561, neighbour = {28, 24, 30}},  -- piece029
		{X = 638, Y = 561, neighbour = {29, 25}}  -- piece030
	}
}

function self.Init(_owner)
	sminigames.SetStandartScriptName(_owner, reveal_image) 
	
	self.LoadInfo(_owner)
	
	self.dragging = -1 -- тащим? 
end

function self.LoadInfo(_owner)
	self.pieces = {}
	for i = 1, #self.params.positions do
		local widget = __cast(_owner.GetWidget(self.params.piece_id..i, true), sf.gui.CImageWidget)
		__assert(widget, "Нет виджета в dsfrontend: "..self.params.piece_id..i)
		widget.SetOffset(self.params.positions[i].X, self.params.positions[i].Y)
		local color = sf.graphics.Color(widget.GetColor())
		color.Alpha = 0
		widget.SetColor(color)
		
		table.insert(self.pieces, widget)
	end
	
	self.clip =  sf.gui.CClipWidget("", 0, 0)
	self.clip.GetClip().Load(self.params.clip, true)
	self.clip.SetOffset(0, 0)
	self.clip.GetClip().Stop()
	self.clip_size = {X = self.clip.GetClip().GetViewSize().X, Y = self.clip.GetClip().GetViewSize().Y}
	self.clip.SetSize(0, 0)
	_owner.AddWidget(self.clip)
end
-- начинаем событие drag-and-drop
function self.OnMouseDown(_owner, _pos, _button, _keyboard_state, _broadcast)
	self.dragging = 1
	if self.clip then
		self.clip.SetSize(self.clip_size.X, self.clip_size.Y)
		self.clip.SetOffset(_pos.X ,_pos.Y + self.params.cursor_height)
		self.clip.GetClip().Play()
	end
	self.OnMouseMove(_owner, _pos, _keyboard_state, _broadcast)
	return true
end 
-- заканчиваем событие drag-and-drop
function self.OnMouseUp(_owner, _pos, _button, _keyboard_state, _broadcast)
	self.dragging = -1
	if self.clip then
		self.clip.GetClip().Stop()
		self.clip.SetSize(0, 0)
		
		if self.params.sound_id then
			local fade = self.params.sound_fade_time or 0
			stop_sound(self.params.sound_id)
		end
	end
	return true
end 
-- должен проверить, не тащимся ли мы по объекту, и если так, то надо увеличить его альфу
function self.OnMouseMove(_owner, _pos, _keyboard_state, _broadcast)
	local cursor = sf.gui.CImageWidget(self.params.cursor, "cursor", 1, 0)
	if cursor then
		sf.gui.g_Cursor.Instance().SetCustomCursor(cursor.GetImage().GetTexture())
	end
	
	if self.dragging < 0 then return false end
	
	if self.params.sound_id then
		sound(self.params.sound_id)
	end
	
	if self.clip then
		self.clip.SetOffset(_pos.X - self.params.cursor_width/2,_pos.Y + self.params.cursor_height/2)
	end
	local ind = self.IsPiece(_pos)
	if ind then
		local color = sf.graphics.Color(self.pieces[ind].GetColor())
		color.Alpha = color.Alpha + self.params.speed
		if color.Alpha > 255 then
			color.Alpha = 255
		end
		self.pieces[ind].SetColor(color)
		-- меняем альфу у соседей
		for i= 1, #self.params.positions[ind].neighbour do
			local index = self.params.positions[ind].neighbour[i]
			local color = sf.graphics.Color(self.pieces[index].GetColor())
			color.Alpha = color.Alpha + self.params.neighbour_alpha
			if color.Alpha > 255 then
				color.Alpha = 255
			end
			self.pieces[index].SetColor(color)
		end
		self.CheckEnd(_owner)
	end
	return true 
end 
-- возвращает элемент, на который сейчас указываем
function self.IsPiece(_pos)
	for i = 1, #self.pieces do
		if  misc.GetRect(self.pieces[i]).IsContains(_pos.X, _pos.Y) 
			and sminigames.IsVisiblePoint(self.pieces[i].GetImage(), 
										_pos.X - self.pieces[i].GetOffset().X, 
										_pos.Y - self.pieces[i].GetOffset().Y) then
				return i				
		end
	end
	return nil
end 

function self.CheckEnd(_owner)
	for i = 1, #self.pieces do
		local color = sf.graphics.Color(self.pieces[i].GetColor())
		if color.Alpha < self.params.min_alpha and self.params.positions[i].should_be_visible then
			return false
		end
	end 
	
	if self.params.sound_id then
		local fade = self.params.sound_fade_time or 0
		stop_sound(self.params.sound_id)
	end
	_owner.SetGameResult(1)
	_owner.OnEndGame()
	return true
end 