mgt_find_and_apply = {}

item_hint_eff = {
	    {key=EFFECTOR_MODIFIER.KEY_OPACITY, start_time = 0.0, time = 0.5, end_value = 0.2},
	    {key=EFFECTOR_MODIFIER.KEY_OPACITY, start_time = 0.5, time = 0.5, end_value = 1.0},
	    {key=EFFECTOR_MODIFIER.KEY_OPACITY, start_time = 1.0, time = 0.5, end_value = 0.2},
	    {key=EFFECTOR_MODIFIER.KEY_OPACITY, start_time = 1.5, time = 0.5, end_value = 1.0},
	    {key=EFFECTOR_MODIFIER.KEY_OPACITY, start_time = 2.0, time = 0.5, end_value = 0.2},
	    {key=EFFECTOR_MODIFIER.KEY_OPACITY, start_time = 2.5, time = 0.5, end_value = 1.0},
	    {key=EFFECTOR_MODIFIER.KEY_OPACITY, start_time = 3.0, time = 0.5, end_value = 0.2},
    }


function mgt_find_and_apply:RestoreStates()  
end

--Инициализация хайден сика
function mgt_find_and_apply:Init(item_list, on_finish, is_counter_type)
    self.name = "find_and_apply"
    self.state = "active" --статус мини-игры
    self.ho_list = {} --список предметов для поиска
    self.types_list  = {} --список типов предметов для поиска
    self.on_finish = on_finish;
    self.is_counter_type = is_counter_type;

    self.ho_list = self:create_ho_list(item_list);

    self.types_list = self:create_types_list()--создаем список 

    self:draw_ho_list(self.types_list)
    HINT_TIME_ACTIVATE = 40
    
    HUDScreen:SetMiniGameMode()
end

--вызрузка при переходе на др екран
function mgt_find_and_apply:UnLoad()
    HUDScreen:UnLoadHO_HUD();
end

function mgt_find_and_apply:SetSuccessSound(_success_sound)  
    self.success_sound = _success_sound;
end

function mgt_find_and_apply:SetFailSound(_fail_sound) 
    self.fail_sound = _fail_sound; 
end
--\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\--
function mgt_find_and_apply:is_where_trigger(where, item_name)
    if(type(self.drag_item.where) == "string" and self.drag_item.where == item_name) then
        return true
    end
    
    if(type(self.drag_item.where) == "table") then
        for key, value in pairs(self.drag_item.where) do
            if(value == item_name) then
                return true;
            end
        end
    end
    
    return false;
end

function mgt_find_and_apply:OnClick(item_name)
    if(self.state ~= "active") then return end
    
    if(self.drag_item == nil) then
        for index, hidden_object in pairs(self.ho_list) do
            if(hidden_object.obj[1] == item_name) then
                self:TakeItem(hidden_object);
            end
        end
    else
        if(item_name == self.drag_item.part.."_where" or self:is_where_trigger(self.drag_item.where, item_name)) then
            self:ApplyObject(self:get_hidden_object_by_name(self.drag_item.part));
        end
        self:ReturnObj();
        
    end
end

function mgt_find_and_apply:OnHint()
    local active_list = {}
    for index, hidden_object in pairs(self.ho_list) do
        if(hidden_object.active and (CurrentScreen.zoom == nil or
                 (hidden_object.zoom and  hidden_object.zoom[1] == CurrentScreen.zoom.name))) then
            table.insert(active_list, hidden_object)
        end
    end
  
    local active_amount = table_size(active_list);
    
    if(active_amount > 0) then
        local rand = math.random(active_amount);
        local item_name = active_list[rand].obj[1];
        local pos_x = active_list[rand].obj[2].x;
        local pos_y = active_list[rand].obj[2].y;
        local hint_name = item_name.."_hint";
        if(active_list[rand].zoom and  CurrentScreen.zoom == nil) then --если предмет внутри зума
            hint_name = active_list[rand].zoom[2];
            pos_x = active_list[rand].zoom[3];
            pos_y = active_list[rand].zoom[4];
        end
        if(active_list[rand].intaractive and GetState(CURRENT_SCREEN, active_list[rand].intaractive[1]) ~= "hide") then --если внутри интерактива
            hint_name = active_list[rand].intaractive[2];
            pos_x = active_list[rand].intaractive[3];
            pos_y = active_list[rand].intaractive[4];
        end
        
        
        local hint_pos_x = nil
        local hint_pos_y = nil
        local texture_path = CurrentScreen.textures_path;
        if(CurrentScreen.zoom) then
            texture_path = CurrentScreen.zoom.textures_path;
        end
        
        local scr = CurrentScreen.zoom or CurrentScreen;
        local is_obj = scr:CreateObj(OBJ_TYPE.NO_ACTIVE, hint_name, texture_path..hint_name, 500, 500);    
       
        if(is_obj == true) then
            
            ItemSetPosition(hint_name, pos_x, pos_y)
            EffectorPlay(item_hint_eff, hint_name, false)
            DelayedExec(3.0, function()
                scr:RemoveItem(hint_name, 0.3)
            end, 113)
        end
        
        return true
    end
    
    return false
end

function mgt_find_and_apply:OnSkip()
    if(self.state ~= "active") then return end

    for index, hidden_object in pairs(self.ho_list) do
        self:TakeItem(hidden_object, true)
        self:ApplyObject(hidden_object, true)
    end
end


function mgt_find_and_apply:OnButtonDown(item_name)
end

function mgt_find_and_apply:ZoomAllItemFound(_zoom_name)
     for key, hidden_object in pairs(self.ho_list) do
        if(hidden_object.active and hidden_object.zoom and hidden_object.zoom[1] == _zoom_name) then
            return false;
        end
    end
    
    return true;
end   

--\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\--
function mgt_find_and_apply:TakeItem(hidden_object, _skipped)
    if(hidden_object.active == false) then return false end
    
    self.drag_item = {}
    
    if(_skipped) then
        local item_name = hidden_object.obj[1]
        self.drag_item.part = item_name;
        self.drag_item.where = hidden_object.where;
        ItemSetOpacity(self.drag_item.part, 0.0);
        
        self.drag_item.full = item_name.."_full";
        self.drag_item.affix = item_name.."_affix";
        
        SetVisibleCursor(false)
    else
        local texture_path = CurrentScreen.textures_path;
        local screen_name = CurrentScreen:GetName()
       
        local item_name = hidden_object.obj[1]
        local is_obj = HUDScreen:CreateObj(OBJ_TYPE.NO_ACTIVE, item_name.."_full", texture_path..item_name.."_full", 500, 500);    
        ItemRemove(screen_name, item_name.."_shadow", 0.2)
            
        if(is_obj == true) then
            
            local x1 = ItemGetX(item_name) + ItemGetWidth(item_name) / 2 - ItemGetWidth(item_name.."_full") / 2;
            local y1 = ItemGetY(item_name) + ItemGetHeight(item_name) / 2 - ItemGetHeight(item_name.."_full") / 2;
            
            self.drag_item.part = item_name;
            self.drag_item.where = hidden_object.where;
            ItemSetOpacity(self.drag_item.part, 0.0);
            
            self.drag_item.full = item_name.."_full";
            self.drag_item.affix = item_name.."_affix";
            
            SetVisibleCursor(false)
            
            ItemSetPosition(self.drag_item.full, messenger_table.mouse_X - ItemGetWidth(self.drag_item.full) / 2, messenger_table.mouse_Y - ItemGetHeight(self.drag_item.full) / 2)
        end 
    end 
end
------------------------------------------------------------------------
function mgt_find_and_apply:ApplyObject(hidden_object, _skipped)
    if(hidden_object.active == false) then return false end

    if(not _skipped) then
        if(self.success_sound) then
            SoundPlay(self.success_sound)
        else
            SoundPlay("sound/affix.ogg")
        end
    end
    
    hidden_object.active = false
    self.types_list = self:create_types_list();
    
    SetState(CURRENT_SCREEN, "found_obj", GetState(CURRENT_SCREEN,"found_obj").." "..hidden_object.obj[1])
    
    local texture_path = CurrentScreen.textures_path;
    local screen_name = CurrentScreen:GetName()
   
    local item_name = hidden_object.affix[1]
    local is_obj = CurrentScreen:CreateObj(OBJ_TYPE.NO_ACTIVE, item_name, texture_path..item_name, hidden_object.affix[2].x, hidden_object.affix[2].y);    
    ItemSetOpacity(item_name, 0.0)
    ItemChangeOpacity(item_name, 1.0, 0.3)
    ItemRemove(CurrentScreen.name, self.drag_item.full, 0.3)
    ItemRemove(CurrentScreen.name, self.drag_item.part)
    self.drag_item = nil;
    
    SetVisibleCursor(true)
    
    if(hidden_object.finding_fun) then
        hidden_object:finding_fun()
    end
    
    DelayedExec(0.5, function()    
        self:AfterTakeItem();
    end, 113)
end
------------------------------------------------------------------------
function mgt_find_and_apply:AfterTakeItem()
    local is_completed = mgt_find_and_apply:IsCompleted();
 
    --DelayedExec(0.9, function()
        self:redraw_ho_list()
        if(is_completed) then
            HINT_TIME_ACTIVATE = 0.01
            mgt_find_and_apply.state = "completed"
            CurrentScreen.mini_game = nil
            if(self.on_finish) then
                self:on_finish();
            end
            
            DelayedExec(0.3, function()
                self:remove_ho_list();
            end, 113) 
        end
    --end)
end
------------------------------------------------------------------------
function mgt_find_and_apply:ReturnObj()
    if(self.drag_item) then
        if(self.fail_sound) then
            SoundPlay(self.fail_sound)
        end
        ItemMoveTo(self.drag_item.full, ItemGetX(self.drag_item.part), ItemGetY(self.drag_item.part), 0.5)
        local part_name = self.drag_item.part;
        local full_name = self.drag_item.full;
        SoundPlay("sound/interface/wrong.ogg")
        DelayedExec(0.4, function()
            ItemChangeOpacity(part_name, 1.0, 0.1)
            ItemRemove(CurrentScreen.name, full_name, 0.1)
        end, 113)
        self.drag_item = nil;
        SetVisibleCursor(true)
    end
end
--\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\--
function mgt_find_and_apply:create_ho_list(item_list)
    for key, value in pairs(item_list) do
        if(self:is_found_item(value.obj[1]))then
            value.active = false;
        else
            value.active = true;
        end
    end
    return item_list;
end
--\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\--
function mgt_find_and_apply:is_found_item(_item_name)
    for found_item in string.gmatch(GetState(CURRENT_SCREEN, "found_obj"), "[_%a%d]+") do
		if(found_item == _item_name) then
		    return true;
		end
    end 
    return false
end
--\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\--

--создаем список содержащий список типов объектов поиска и количеством еще не найденных объектов каждого типа на сцене
--необходимо для отображения на экране списка объектов поиска
function mgt_find_and_apply:create_types_list()   
    local types_list = {}
    
    for ho_index, hidden_object in pairs(self.ho_list) do
        local is_exist = false
        for types_index, obj_type in pairs(types_list) do --проверяем есть ли уже объекты данного типа в списке типов
            if(self:GetItemType(hidden_object.obj[1]) == obj_type.type_name) then
                if(hidden_object.active) then
                    if(hidden_object.amount == nil) then
                        obj_type.amount = obj_type.amount + 1;
                    else
                        obj_type.amount = obj_type.amount + hidden_object.amount;
                    end
                end
                is_exist = true
            end
        end    
        
        if(is_exist == false) then --если нет, добавляем в список новый тип
            if(hidden_object.active ~= false) then
                if(hidden_object.amount == nil) then
                    table.insert(types_list, {type_name = self:GetItemType(hidden_object.obj[1]), amount = 1})
                else
                    table.insert(types_list, {type_name = self:GetItemType(hidden_object.obj[1]), amount = hidden_object.amount})
                end
            else
                table.insert(types_list, {type_name = self:GetItemType(hidden_object.obj[1]), amount = 0})
            end
        end
    end
    
    return types_list;
end
--\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\--
function mgt_find_and_apply:IsExistType(t, v)
 	local itemType1 = self:GetItemType(v)
	    
    for key, value in pairs(t) do
	    local itemType2 = self:GetItemType(value.name)
	    
        if(itemType1 == itemType2) then
            return key;
        end
    end
    
    return false
end

function mgt_find_and_apply:GetItemType(item_name)
    local pos = string.find(item_name, "_%d")
	local item_type = (pos and pos > 0) and string.sub(item_name, 0, pos - 1) or item_name
	
	return item_type;
end

function mgt_find_and_apply:IsCompleted()
    for key, hidden_object in pairs(self.ho_list) do
        if(hidden_object.active ~= false) then
            return false;
        end
    end
    
    return true;
end
-----------------------------------------------------------------------------------
function mgt_find_and_apply:get_hidden_objects_count()
    local count = 0;
    for type_index, type_value in pairs(self.types_list) do
        count = count + type_value.amount;
    end
    
    return count;
end
-----------------------------------------------------------------------------------
function mgt_find_and_apply:get_hidden_object_by_name(obj_name)
    for index, hidden_object in pairs(self.ho_list) do
        if(hidden_object.obj[1]  == obj_name) then
            return hidden_object;
        end
    end
  
    
    return nil;
end
-----------------------------------------------------------------------------------
function mgt_find_and_apply:redraw_ho_list()
    if(self.is_counter_type) then
        local string = tostring(self:get_hidden_objects_count())
        SetLabelText("counter_text", string)
        ItemSetPosition("counter_text", 55 - ItemGetWidth("counter_text") / 2, 1117)
    else
        local index = 0
        for type_index, type_value in pairs(self.types_list) do
            local string = GetString(type_value.type_name);
            
            if(type_value.amount == 0) then 
                ItemSetColor("item_"..index, 0.5, 0.5, 0.5, 1.0)
                SetLabelText("item_"..index, string)
            elseif(type_value.amount == 1) then 
                SetLabelText("item_"..index, string)
            elseif(type_value.amount > 1) then
                string = GetString(type_value.type_name.."_m");
                SetLabelText("item_"..index, string)
            end  
            index = index + 1
        end
    end
end

function mgt_find_and_apply:draw_ho_list() 
    HUDScreen:LoadHO_HUD(self.is_counter_type)
   
    if(self.is_counter_type) then
        local string = tostring(self:get_hidden_objects_count())
        HUDScreen:CreateLabel("counter_text", string, 35, 1117, 53, FONT_QUICKSAND)
        ItemSetPosition("counter_text", 55 - ItemGetWidth("counter_text") / 2, 1117)
        ItemSetSize("counter_text", 60, 30)
        ItemSetColor("counter_text", 1.0, 1.0, 1.0, 1.0)
    else
        local index = 0
        for type_index, type_value in pairs(self.types_list) do
            local string = GetString(type_value.type_name);
            if(type_value.amount > 1) then 
                string = GetString(type_value.type_name.."_m");
            end
                   
            local label_name = "item_"..index
            HUDScreen:CreateLabel(label_name, string, 20, (780 + index * 32), 20, FONT_UNDERWOOD)

            ItemSetSize(label_name, 250, 30)
            ItemSetColor(label_name, 0, 0, 0, 1.0)
            if(type_value.amount == 0) then 
                ItemSetColor(label_name, 0.5, 0.5, 0.5, 1.0)
            end
            SetLabelAlign(label_name, TEXT_ALIGN.H_LEFT)
            
            index = index + 1
        end
    end
    
    ItemSetOpacity("ho_panel", 0.0)
    ItemChangeOpacity("ho_panel", 1.0, 1.0)
end

function mgt_find_and_apply:remove_ho_list()
    if(self.is_counter_type) then
        HUDScreen:RemoveItem("counter_text", 1.0)
    else
        local index = 0
        for type_index, type_value in pairs(self.types_list) do
            HUDScreen:RemoveItem("item_"..index.."_shadow", 1.0)
            HUDScreen:RemoveItem("item_"..index, 1.0)
            index = index + 1
        end
    end
    HUDScreen:UnLoadHO_HUD(1.0);
end

function mgt_find_and_apply:OnKeyDown(key)
	if(key == VK_SPACE) then
		--skip_fun();
	end
end

function mgt_find_and_apply:on_hide_drag_object()
    if(self.drag_item) then
        SetVisibleCursor(true)
        ItemSetOpacity(self.drag_item.full, 0.0)
    end
end

function mgt_find_and_apply:OnMouseMove(item_name)
    if(self.drag_item) then
        if(item_name == "skip" or item_name == "menu_button" or item_name == "hint") then
            SetVisibleCursor(true)
            ItemSetOpacity(self.drag_item.full, 0.0)
        else
            SetVisibleCursor(false)
            ItemSetOpacity(self.drag_item.full, 1.0)
        end
    end
end

function mgt_find_and_apply:Update()  
    if(self.drag_item) then
        ItemSetPosition(self.drag_item.full, messenger_table.mouse_X - ItemGetWidth(self.drag_item.full) / 2, messenger_table.mouse_Y - ItemGetHeight(self.drag_item.full) / 2)
    end
end
--//////////////////////////////////////////////////////////////////////////////////////
