--////////////////////////////////////////////////////////////////////////////
--//                                                                        //
--//	                     Script: Invasão	                            //
--//                         Modificado por: HyoN                           //
--//                         WhatsApp:	(75) 9 8851-1936                    //
--//                                                                        //
--////////////////////////////////////////////////////////////////////////////


INVASION_SWITCH = 0 --(1 ativa / 0 desativa o sistema)

INVASION_COMMANDSTART = "/iniciarinvasao" -- Exemplo: /iniciarinvasao 1 = Starta a invasão da index 1
INVASION_COMMANDEND = "/finalizarinvasao" -- Exemplo: /finalizarinvasao = Finaliza a invasão ativa


--Index é usado para identificar qual invasão está funcionando (Não utilize 0)
--Day of Week, Day, Hour, Minute
--Day of Week: 0 a 6: Domingo, segunda, terça, quarta, quinta, sexta, sabado
--Day of Week: -1 = Day
--Day = -1 = Horas e minutos.
--Exemplo: rodará todos os dias as 20h15min
--Exemplo 02: rodará todo dia 05 ás 15h00min
--Exemplo 03: rodará todo sábado as 15h00min
--Exemplo 03: rodará todos os dias as 15h00min


local CONFIG_INVASION_DATE = {
--[1] index invasão
{index = 1, dayofweek = -1, day = -1, hour = 02, minute = 01},
{index = 1, dayofweek = -1, day = -1, hour = 05, minute = 01},
{index = 1, dayofweek = -1, day = -1, hour = 08, minute = 01},
{index = 1, dayofweek = -1, day = -1, hour = 11, minute = 01},
{index = 1, dayofweek = -1, day = -1, hour = 14, minute = 01},
{index = 1, dayofweek = -1, day = -1, hour = 17, minute = 01},
{index = 1, dayofweek = -1, day = -1, hour = 20, minute = 01},
{index = 1, dayofweek = -1, day = -1, hour = 23, minute = 01},

--[2] index invasão
{index = 2, dayofweek = -1, day = -1, hour = 02, minute = 16},
{index = 2, dayofweek = -1, day = -1, hour = 05, minute = 16},
{index = 2, dayofweek = -1, day = -1, hour = 08, minute = 16},
{index = 2, dayofweek = -1, day = -1, hour = 11, minute = 16},
{index = 2, dayofweek = -1, day = -1, hour = 14, minute = 16},
{index = 2, dayofweek = -1, day = -1, hour = 17, minute = 16},
{index = 2, dayofweek = -1, day = -1, hour = 20, minute = 16},
{index = 2, dayofweek = -1, day = -1, hour = 23, minute = 16},

--{index = 3, dayofweek = -1, day = -1, hour = 01, minute = 00},
--{index = 3, dayofweek = -1, day = -1, hour = 04, minute = 00},
--{index = 3, dayofweek = -1, day = -1, hour = 07, minute = 00},
--{index = 3, dayofweek = -1, day = -1, hour = 10, minute = 00},   
--{index = 3, dayofweek = -1, day = -1, hour = 13, minute = 00},
--{index = 3, dayofweek = -1, day = -1, hour = 16, minute = 00},
--{index = 3, dayofweek = -1, day = -1, hour = 19, minute = 00},
--{index = 3, dayofweek = -1, day = -1, hour = 22, minute = 00},
--
--{index = 4, dayofweek = -1, day = -1, hour = 01, minute = 05},
--{index = 4, dayofweek = -1, day = -1, hour = 04, minute = 05},
--{index = 4, dayofweek = -1, day = -1, hour = 07, minute = 05},
--{index = 4, dayofweek = -1, day = -1, hour = 10, minute = 05},   
--{index = 4, dayofweek = -1, day = -1, hour = 13, minute = 05},
--{index = 4, dayofweek = -1, day = -1, hour = 16, minute = 05},
--{index = 4, dayofweek = -1, day = -1, hour = 19, minute = 05},
--{index = 4, dayofweek = -1, day = -1, hour = 22, minute = 05},
}

--Nome da Invasão
--Duração (min)
--Anunciar no global os monstros vivos 1 = sim 0 = não
--Anunciar no global quem matou 1 = sim 0 = não
-- Habilita o sistema ranqueado 1 sim 0 = não (cada monstro morto equivale a um ponto no ranking configurado)
-- Coluna para adicionar a pontuação no ranking (Obrigatório caso o sistema ranqueado esteja ativo)

--//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
--//																													  //
--//          OBS: COLUNA DEVERÁ EXISTIR NA TABELA CHARACTER DA DB MuOnline para o sistema funcionar corretamente         //
--//                          << RODE A QUERY ABAIXO PARA CRIAR UMA COLUNA NO LUGAR CORRETO >>                            //
--//                    ALTER TABLE [dbo].[Character] ADD [NomeDaColuna] [int] NOT NULL DEFAULT ((0))                     //
--//																													  //
--//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



local CONFIG_INVASION_SYSTEM = {}

--[1] index invasão
CONFIG_INVASION_SYSTEM[1] = {
    name = "Noria - Rankeado", duration = 12, announce_global = 1, announce_death = 0, ranqueada = 1, column = "Invasion"
	

}
--[2] index invasão
CONFIG_INVASION_SYSTEM[2] = {
    name = "Noria - Rankeado", duration = 12, announce_global = 1, announce_death = 0, ranqueada = 1, column = "Invasion"
   -- name = "Invasion Noria - Rankeado", duration = 2, announce_global = 1, announce_death = 1, ranqueada = 1, column = nil
}

--CONFIG_INVASION_SYSTEM[3] = {
--    name = "5 GUARDIÕES de Devias apareceu entre as ruínas, vá Desafia-lo!", duration = 50, announce_global = 1, announce_death = 0, ranqueada = 0, column = nil
--   -- name = "Invasion Noria - Rankeado", duration = 2, announce_global = 1, announce_death = 1, ranqueada = 1, column = nil
--}
--
--CONFIG_INVASION_SYSTEM[4] = {
--    name = "5 CAMPEÕES de Tarkan apareceu entre as aréias do deserto, tente Derrota-lo!", duration = 50, announce_global = 1, announce_death = 0, ranqueada = 0, column = nil
--   -- name = "Invasion Noria - Rankeado", duration = 2, announce_global = 1, announce_death = 1, ranqueada = 1, column = nil
--}


--Index (Invasion) (Não utilize 0)
--Class Monster
--Map
--Quantia
local INVASION_MONSTER_CREATE = {}

--[1] index invasão
INVASION_MONSTER_CREATE[1] = {
    {class = 308, map = 3, count = 60},
}
--[2] index invasão
INVASION_MONSTER_CREATE[2] = {
    {class = 306, map = 3, count = 60},
}

--INVASION_MONSTER_CREATE[3] = {
--    {class = 321, map = 2, count = 5},
--}
--
--INVASION_MONSTER_CREATE[4] = {
--    {class = 322, map = 8, count = 5},
--}




--Class Monster
--Item Section
--Item Index
--Level
--Luck
--Skill
--Opt
--Exc
--Count
local MONSTER_DROP_CLASS = {}

--[1] index invasão
MONSTER_DROP_CLASS[1] = {
    { class = 308, section = 14, item_index = 217, level = 0, luck = 0, skill = 01, opt = 0, exc = 0, count = 1},
}
--[2] index invasão
MONSTER_DROP_CLASS[2] = {
    { class = 306, section = 14, item_index = 218, level = 0, luck = 0, skill = 01, opt = 0, exc = 0, count = 1},
}

--MONSTER_DROP_CLASS[3] = {
--    { class = 321, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--    { class = 321, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--    { class = 321, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--    { class = 321, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--    { class = 321, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--
--}
--
--MONSTER_DROP_CLASS[4] = {
--    { class = 322, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--    { class = 322, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--    { class = 322, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--    { class = 322, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--    { class = 322, section = 14, item_index = 215, level = 0, luck = 0, skill = 0, opt = 0, exc = 0, count = 1},
--}

local INVASION_MESSAGES = { }

INVASION_MESSAGES["Por"] = {
[1] = "A Invasão: %s começou!!!",
[2] = "A Invasão: %s acabou!!!",
[3] = "%s matou um %s",
[4] = "Restam %d Monstros vivos!",
}

INVASION_MESSAGES["Eng"] = {
[1] = "The Invasion: %s has started !!!",
[2] = "The Invasion: %s is over !!!",
[3] = "%s killed a %s",
[4] = "%d monsters left alive!",
}

INVASION_MESSAGES["Spn"] = {
[1] = "¡¡¡La invasión: %s ha comenzado !!!",
[2] = "La invasión: ¡¡¡ %s terminó !!!",
[3] = "%s mató a %s",
[4] = "¡%d monstruos quedan vivos!",
}


--Sistema do script, fazer backup antes de alterar algo.
Invasion = {}

--System
local INVASION_MONSTERS = {}
local INVASION_SYSTEM = {COLUMN = nil}
local INVASION_ITEMS_RAND = {}
local INVASION_SHOW = {QTD = 0, HOUR = "00:00:00", DURATION = "00"}
local Player = { index = nil}
local RankedSystem = 0

function Invasion.Init()
    if INVASION_SWITCH ~= 1
    then
        return
    end
    
	Commands.Register(INVASION_COMMANDSTART, Invasion.CommandStart)
	Commands.Register(INVASION_COMMANDEND, Invasion.CommandEnd)
    GameServerFunctions.MonsterDie(Invasion.MonsterDie)
	GameServerFunctions.MonsterDieGiveItem(Invasion.MonsterDieGiveItem)
	Invasion.Load()
	Timer.Interval(1, Invasion.Load2)
    Timer.Interval(1, Invasion.Running)

    for i in ipairs(CONFIG_INVASION_DATE) do
		if CONFIG_INVASION_DATE[i].dayofweek ~= -1
		then
			Schedule.SetDayOfWeek(CONFIG_INVASION_DATE[i].dayofweek, CONFIG_INVASION_DATE[i].hour, CONFIG_INVASION_DATE[i].minute, Invasion.Start, CONFIG_INVASION_DATE[i].index)
		elseif CONFIG_INVASION_DATE[i].day ~= -1
		then
			Schedule.SetDayAndHourAndMinute(CONFIG_INVASION_DATE[i].day, CONFIG_INVASION_DATE[i].hour, CONFIG_INVASION_DATE[i].minute, Invasion.Start, CONFIG_INVASION_DATE[i].index)
		else
			Schedule.SetHourAndMinute(CONFIG_INVASION_DATE[i].hour, CONFIG_INVASION_DATE[i].minute, Invasion.Start, CONFIG_INVASION_DATE[i].index)
		end
	end
end

function Invasion.CommandStart(aIndex, Arguments)

    local index = command:getNumber(Arguments, 1)
	local player = User.new(aIndex)

	local player = User.new(aIndex)
	
    --if player:getAuthority() ~= 32
    --then
--		return
  --  end
	
	local index = command:getNumber(Arguments, 1)
	
	
	
	if index == nil or index == 0 or CONFIG_INVASION_SYSTEM[index] == nil
	then
        SendMessage(string.format("[Sistema] Invasão má configurada, entre em contato com a administração."), aIndex, 1)
        return
    end
    
	if System == 1
	then
	    SendMessage(string.format("[Sistema] Já existe uma invasão em andamento."), aIndex, 1)
	    return
	end
	
    INVASION_SHOW.INDEX = index
    Invasion.Start(index)
end

function Invasion.Load()
    for aIndex = 9000,9999 do
		local player = User.new(aIndex)	
		if player:getConnected() == 3
		then
			if RankedSystem == 1
			then
			    if INVASION_SYSTEM.COLUMN ~= nil
	            then
				    -- Monster Number
	                CreatePacket ("MonsterQtd", 0x17)
	                SetDwordPacket("MonsterQtd", INVASION_SHOW.QTD)
	                SendPacket("MonsterQtd", aIndex)
	                ClearPacket("MonsterQtd")
	                DataBase.SetValue("Character", "IVCheckPoints", 0, "Name", player:getName())
	                	
	                if RankedSystem == 1
	                then
					    --Icon Show
	                    CreatePacket ("Invasion", 0x17)
	                    SetBytePacket("Invasion", 1)
	                    SendPacket("Invasion", aIndex)
	                    ClearPacket("Invasion")

	                    if INVASION_SYSTEM.COLUMN ~= nil
	                    then
	                        --QtdPointsTotal
	                        local PR = DataBase.GetValue("Character", INVASION_SYSTEM.COLUMN, "Name", player:getName())
                            CreatePacket ("IVInfo", 0x17)
                            SetDwordPacket("IVInfo", PR)
                            SendPacket("IVInfo", aIndex)
                            ClearPacket("IVInfo")
	                        
	                        --QtdPointSetValue
	                        local PQ = DataBase.GetValue("Character", "IVCheckPoints", "Name", player:getName())
	                        CreatePacket ("IVPoints", 0x17)
	                        SetDwordPacket("IVPoints", PQ)
	                        SendPacket("IVPoints", aIndex)
	                        ClearPacket("IVPoints")
	                    end
					else
					    --Icon Kill
	                    CreatePacket ("Invasion", 0x17)
	                    SetBytePacket("Invasion", 0)
	                    SendPacket("Invasion", aIndex)
	                    ClearPacket("Invasion")
	              	end		        
			    end
			end
		end
	end
end

function Invasion.Check()
    local aIndex = Player.index
	
    if aIndex == nil
	then
	    return
	end
	
    local player = User.new(aIndex)
	
	if RankedSystem == 1
	then
	    CreatePacket ("Invasion", 0x17)
	    SetBytePacket("Invasion", 1)
	    SendPacket("Invasion", aIndex)
	    ClearPacket("Invasion")
		
		--Monstro Quantidade Vivos
		CreatePacket ("MonsterQtd", 0x17)
	    SetDwordPacket("MonsterQtd", INVASION_SHOW.QTD)
	    SendPacket("MonsterQtd", aIndex)
	    ClearPacket("MonsterQtd")
		
		--Duração Invasao
		CreatePacket ("Duration", 0x17)
	    SetBytePacket("Duration", INVASION_SHOW.DURATION)
	    SendPacket("Duration", aIndex)
	    ClearPacket("Duration")
		
		--Inicio Hora Invasao
		CreatePacket ("Hour", 0x17)
	    SetCharPacket("Hour", INVASION_SHOW.HOUR)
	    SendPacket("Hour", aIndex)
	    ClearPacket("Hour")
	else
        --Kill Icon	
	    CreatePacket ("Invasion", 0x17)	
		SetBytePacket("Invasion", 0)	
		SendPacket("Invasion", aIndex)	
		ClearPacket("Invasion")	
		----QtdPoints
        DataBase.SetValue("Character", "IVCheckPoints", 0, "Name", player:getName())
        local PQ = DataBase.GetValue("Character", "IVCheckPoints", "Name", player:getName())
        CreatePacket ("IVPoints", 0x17)
        SetDwordPacket("IVPoints", PQ)
        SendPacket("IVPoints", aIndex)
        ClearPacket("IVPoints")
	end
end

function Invasion.Load2()
    for aIndex = 9000,9999 do
		local player = User.new(aIndex)
		if player:getConnected() == 3
		then
			Player.index = player:getIndex()
		else
			Player.index = nil
		end
		
		Invasion.Check()
	end
end

function Invasion.Start(index)
    local getInvasion = CONFIG_INVASION_SYSTEM[index]
    if getInvasion ~= nil
    then
		if getInvasion.ranqueada == 1
		then
		    RankedSystem = 1
			INVASION_SYSTEM.COLUMN = getInvasion.column
		else 
		    RankedSystem = 0
		end
	    System = 1
        Message.SendMessageGlobalMultLangArgs(INVASION_MESSAGES, 1, 0, getInvasion.name)
		INVASION_SHOW.DURATION = getInvasion.duration
		INVASION_SHOW.HOUR = string.format(os.date"%X")
		INVASION_SHOW.INDEX  = index
        local monsterInvasion = INVASION_MONSTER_CREATE[index]
        if monsterInvasion ~= nil
        then
            for n=1, #monsterInvasion do
                local monster = monsterInvasion[n]
                if monster ~= nil
                then
                    Invasion.CreateMonster(index, monster.class, monster.map, monster.count)
                end
            end
        end

        table.insert(INVASION_SYSTEM, 
                    { _index = index, 
                    _end = getInvasion.duration * 60,
                    _state = true,
                    _running = true, 
                    _Name = getInvasion.name,
                    _Announce_Death = getInvasion.announce_death,
                    _Announce_Global = getInvasion.announce_global,
                    _Ranked = getInvasion.ranqueada}
                    )
					
		for key = 1, #INVASION_SYSTEM do			
		    local invasionInfo = INVASION_SYSTEM[key]			
		    INVASION_SHOW.QTD = math.abs(Invasion.GetCountMonsterByInvasion(invasionInfo._index) - 1) + 1		
		end			
		
		Invasion.Load()
    end
end

function Invasion.Running()
    if #INVASION_SYSTEM <= 0
    then
        return
    end
	

    for n = 1, #INVASION_SYSTEM do
        local getInvasion = INVASION_SYSTEM[n]

        if getInvasion ~= nil
        then
            if getInvasion._running == true
            then
                if getInvasion._end <= 0
                then
                    Invasion.InvasionEnd(n)
                else
                    getInvasion._end = getInvasion._end - 1
                end
            end
        end
    end
end

function Invasion.CreateMonster(invasion, class, map, count)
    for i = 1, count do
		local index = AddMonster(map)
		
		if index == -1
		then
			LogAdd(string.format("[Invasion] Problema ao criar o monstro :%d", class))
			return
		end
		
		local monster = User.new(index)
		
		SetPositionMonster(index, map)
		SetMonster(index, class)
		
		monster:setRegenTime(0)
		
		LogAdd(string.format("[Invasion] Class:%d Map:%d CoordX:%d CoordY:%d",class, monster:getMapNumber(), monster:getX(), monster:getY()))
		
        INVASION_MONSTERS[index] = {_index = index, invasionIndex = invasion, class = class}
	end
end

function Invasion.InvasionEnd(invasion)
    local getInvasion = INVASION_SYSTEM[invasion]

    if getInvasion == nil
    then
        return
    end

	--Anunciar no global o fim da 
	Message.SendMessageGlobalMultLangArgs(INVASION_MESSAGES, 2, 0, getInvasion._Name)
	
	--Remove os monstros
	Invasion.ClearInvasionBy(invasion)
	
	--Limpar sistema de invasão
	Invasion.ClearSystemByInvasion(invasion)
	
	--Limpar sistema de ranqueada
	RankedSystem = 0
	System = 0
	INVASION_SYSTEM.COLUMN = nil
end

function Invasion.ClearInvasionBy(index)
	local getInvasion = INVASION_SYSTEM[index]

    if getInvasion == nil
    then
        return
    end

    --Remover monstros caso exista algum vivo
    Invasion.ClearByMonster(getInvasion._index)
end

function Invasion.ClearByMonster(index)
    for key in pairs(INVASION_MONSTERS) do
		if INVASION_MONSTERS[key].invasionIndex == index
		then
			if INVASION_MONSTERS[key]._index ~= -1
			then
				gObjDel(INVASION_MONSTERS[key]._index)
				INVASION_MONSTERS[key] = nil
            else
                INVASION_MONSTERS[key] = nil
			end
		end
	end

end

function Invasion.ClearSystemByInvasion(index)
    local getInvasion = INVASION_SYSTEM[index]

    if getInvasion == nil
    then
        return
    end

    INVASION_SYSTEM[index] = nil
end

function Invasion.DelByMonster(invasion, index)

	for key in pairs(INVASION_MONSTERS) do
		if INVASION_MONSTERS[key].invasionIndex == invasion
		then
			if INVASION_MONSTERS[key]._index == index
			then
				if INVASION_MONSTERS[key]._index ~= -1
				then
					gObjDel(INVASION_MONSTERS[key]._index)
					
					INVASION_MONSTERS[key]._index = -1
				end
			end
		end
	end
end

function Invasion.GetByMonster(invasion, index)
	if INVASION_MONSTERS[index] == nil
	then
		return -1
	end
	
	if INVASION_MONSTERS[index]._index == -1
	then
		return -1
	end
	
	if INVASION_MONSTERS[index].invasionIndex == invasion
	then
		return INVASION_MONSTERS[index]._index
	end
	
	return -1
end

function Invasion.GetCountMonsterByInvasion(invasion)
	local count = 0

	for key in pairs(INVASION_MONSTERS) do
		if INVASION_MONSTERS[key].invasionIndex == invasion
		then
			if INVASION_MONSTERS[key]._index ~= -1
			then
				count = count + 1
			end
		end
	end
	
	return count
	
end

function Invasion.InsertItens(item)
	InsertKey(INVASION_ITEMS_RAND, item)
end

function Invasion.GetItemRand()
	if #INVASION_ITEMS_RAND > 0
	then
		return GetRand(1, #INVASION_ITEMS_RAND)
	end
	
	return -1
end

function Invasion.DropItemByMonster(index, Player, Monster)
	INVASION_ITEMS_RAND = {}

	local monster = User.new(Monster)
    local monsterDrop = MONSTER_DROP_CLASS[index]

    if monsterDrop ~= nil
    then
        for i = 1, #monsterDrop do 
            local monsterInfo = monsterDrop[i]

            if monsterInfo ~= nil
            then
                if monsterInfo.class == monster:getClass()
                then
                    Invasion.InsertItens(monsterInfo)
                end
            end
        end
    end
	
	local key_rand = Invasion.GetItemRand()
	
	if key_rand == -1
	then
		LogAdd("[Invasion] Existe uma má configuração no sistema de dropar item")
		return
	end

    local player = User.new(Player)
	
	local ItemDrop = INVASION_ITEMS_RAND[key_rand]
	
	for i = 1, ItemDrop.count do
		ItemSerialCreate(Player, player:getMapNumber(), player:getX(), player:getY(), GET_ITEM(ItemDrop.section, ItemDrop.item_index), ItemDrop.level, 255, ItemDrop.luck, ItemDrop.skill, ItemDrop.opt, ItemDrop.exc)
	end
end

function Invasion.MonsterDie(Player, Monster)
    if #INVASION_SYSTEM <= 0
    then
        return
    end

    local player = User.new(Player)
	local monster = User.new(Monster)
	local aIndex = player:getIndex()
	
	for key = 1, #INVASION_SYSTEM do
        local invasionInfo = INVASION_SYSTEM[key]

        if invasionInfo ~= nil
        then
            if invasionInfo._running == true
            then
                if Invasion.GetByMonster(invasionInfo._index, Monster) == Monster
                then
				    --Mostrar quantidade de monstros na interface
					INVASION_SHOW.QTD = math.abs(Invasion.GetCountMonsterByInvasion(invasionInfo._index) - 1)
					if INVASION_SYSTEM.COLUMN ~= nil
					then
				        if RankedSystem == 1
					    then
				            --Adicionar pontuação no ranking
					         DataBase.SetAddValue("Character", INVASION_SYSTEM.COLUMN, 1, "Name", player:getName())
					         local PR = DataBase.GetValue("Character", INVASION_SYSTEM.COLUMN, "Name", player:getName())
					         CreatePacket ("IVInfo", 0x17)
					         SetDwordPacket("IVInfo", PR)
					         SendPacket("IVInfo", aIndex)
					         ClearPacket("IVInfo")
					         
					         -- Enviar quantidade de pontos na invasão atual
					         DataBase.SetAddValue("Character", "IVCheckPoints", 1, "Name", player:getName())
					         local PQ = DataBase.GetValue("Character", "IVCheckPoints", "Name", player:getName())
					         CreatePacket ("IVPoints", 0x17)
					         SetDwordPacket("IVPoints", PQ)
					         SendPacket("IVPoints", aIndex)
					         ClearPacket("IVPoints")
					         
					         if INVASION_SHOW.QTD > 0
					         then
					             CreatePacket ("MonsterQtd", 0x17)
					             SetDwordPacket("MonsterQtd", INVASION_SHOW.QTD)
					             SendPacket("MonsterQtd", aIndex)
					             ClearPacket("MonsterQtd")
					         end
					    end
					end
					
				    -- Mostrar no global a quantidade de monstros vivos
					if invasionInfo._Announce_Global == 1
                    then
					    SendMessageGlobal(string.format("[Invasão %s]", invasionInfo._Name),0)
					    SendMessageGlobal(string.format("Restam %d monstros vivos", INVASION_SHOW.QTD),0)
					end
					
                    --Monstrar no global que o player X matou o monstro X
                    if invasionInfo._Announce_Death == 1
                    then
                        Message.SendMessageGlobalMultLangArgs(INVASION_MESSAGES, 3, 33, player:getName(), monster:getName())
                    end
                    
					--Finalizar a invasão mataram todos monstros
					if INVASION_SHOW.QTD <= 0
					then
					    Timer.TimeOut(2, Invasion.InvasionEnd, key)
					end
                end
            end
        end
	end
end

function Invasion.MonsterDieGiveItem(Player, Monster)
    if #INVASION_SYSTEM <= 0
    then
        return 0
    end

    for key = 1, #INVASION_SYSTEM do
        local invasionInfo = INVASION_SYSTEM[key]

        if invasionInfo ~= nil
        then
            if invasionInfo._running == true
            then
                if Invasion.GetByMonster(invasionInfo._index, Monster) == Monster
                then
                    --Sistema onde vai gerar 1 item aleatório
                    Invasion.DropItemByMonster(invasionInfo._index, Player, Monster)
                    
                    --Remover o monstro do sistema
                    Invasion.DelByMonster(invasionInfo._index, Monster)
                    return 1
                end
            end
        end
	end

    return 0
end

function Invasion.CommandEnd(aIndex, Arguments)
    local getInvasion = INVASION_SYSTEM[1]
	local player = User.new(aIndex)
	
    --if player:getAuthority() ~= 32
    --then
--		return
 --   end

	if INVASION_SHOW.INDEX == 0
	then
        SendMessage(string.format("[Sistema] Invasão má configurada, entre em contato com a administração."), aIndex, 1)
        return
    end
    
	if System == 0
	then
	    SendMessage(string.format("[Sistema] Não existe uma invasão em andamento."), aIndex, 1)
	    return
	end

    getInvasion._end = 0
end

Invasion.Init()

return Invasion