local _, core = ...;

-- POSITION MODE --
local posName = {core.L["Gauche"],core.L["Milieu-Gauche"],core.L["Milieu"],core.L["Milieu-Droite"],core.L["Droite"],core.L["Joueur"]};
local currentBgFightScene      = nil;
local currentPositionForSaving = 1;
-- END POSITION MODE --


-- FIGHT MODE VALUES --
local currentAddon        = "";
local incr_IsInFight      = 0; -- pour checker si c'est le même combat pour que les triggers ne se déclenche pas si ce n'est pas le cas
local curr_incr_IsInFight = 0;
local curr_infoFight      = nil;
local currentTurn         = 0;
local currentTurnTime     = 0;
local currentCasting      = {};
local currentShowTooltip  = 0;
local lastTriggerPos      = {};
local CurrMobsFight       = {0, 0, 0, 0, 0, 0};
local DisplayMobsFight    = {0, 0, 0, 0, 0, 0};
local AnimBaseMobsFight   = {0, 0, 0, 0, 0, 0};
local WeaponMobsFight     = {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}};
local PdvMobsFight        = {0, 0, 0, 0, 0, 0};
local DamageMobsFight     = {0, 0, 0, 0, 0, 0};
local IsStunMobsFight     = {0, 0, 0, 0, 0, 0};
local IsSilenceMobsFight  = {0, 0, 0, 0, 0, 0};
local IsInvulMobsFight    = {0, 0, 0, 0, 0, 0};
local CdSpellMobsFight    = {{}, {}, {}, {}, {}, {}};
local EffectMobsFight     = {{}, {}, {}, {}, {}, {}};
local ListEventsSpells    = {{}, {}, {}, {}, {}, {}};
local ListBanSpells       = {};
local JustSummoned        = {false, false, false, false, false, false};
local orderFrameLevel     = {1,5,2,4,3,6};
-- PLAYER VALUES --
local selectedSpell = 0;
local selectedMob   = 0;
local canPlay       = false;
-- END FIGHT MODE VALUES --


-- ===== POPUP DIALOGS ===== --
StaticPopupDialogs["AdventureVictoryPopup"] = {
	text = core.L["Victory"],
	button1 = core.L["Next"],
	OnAccept = function()
		_G["WC_AdventureFightScene"]:Hide();
	end,
	hideOnEscape = false,
	whileDead = true,
}

StaticPopupDialogs["ConfirmReset"] = {
	text = core.L["Cela vous coûtera 1 point de compétence pour être soigné, continuer ?"],
	button1 = core.L["BtnRez"],
	button2 = core.L["Abandonner"],
	OnAccept = function()
		DBProfile.skillPoints = DBProfile.skillPoints - 1;
		_G["SkillPointsCampaignsAdventure"]:SetText(DBProfile.skillPoints);
		ShowFightSceneAdventure(curr_infoFight, nil, currentAddon);
	end,
	OnCancel = function()
		_G["WC_AdventureFightScene"]:Hide();
	end,
	hideOnEscape = false,
	whileDead = true,
}

StaticPopupDialogs["AdventureDefeatPopup"] = {
	text = core.L["Defeat"],
	button1 = core.L["Restart"],
	button2 = core.L["Abandonner"],
	OnAccept = function()
		if currentAddon == "WCC" or (WC_AdventuresData.victories[curr_infoFight.idAdventure] and
									WC_AdventuresData.victories[curr_infoFight.idAdventure] >= btnFightSelected["WC"].index) then
			ShowFightSceneAdventure(curr_infoFight, nil, currentAddon);
		elseif currentAddon == "WC" then
			StaticPopup_Show("ConfirmReset");
		end
	end,
	OnCancel = function()
		_G["WC_AdventureFightScene"]:Hide();
	end,
	hideOnEscape = false,
	whileDead = true,
}

StaticPopupDialogs["AdventureDefeatPopupNoSkill"] = {
	text = core.L["Defeat"],
	button1 = core.L["Abandonner"],
	OnAccept = function()
		_G["WC_AdventureFightScene"]:Hide();
	end,
	hideOnEscape = false,
	whileDead = true,
}

StaticPopupDialogs["FFAdventure"] = {
	text = core.L["Abandonner"]..core["?"],
	button1 = core.L["Oui"],
	button2 = core.L["Non"],
	OnAccept = function()
		incr_IsInFight = incr_IsInFight + 1;
		_G["WC_AdventureFightScene"]:Hide();
	end,
	hideOnEscape = false,
	whileDead = true,
}

-- TOOLTIP --
OnEnterTooltipEnnemyAdventureFight = function(self, motion)
	currentShowTooltip = self.pos;

	if not self.unit and not self.idUnit then return end
	if self.unit == 0 then return end
	
	local anchor = self.Anchor or {"ANCHOR_LEFT", 0, 0};
	GameTooltip:SetOwner(self, anchor[1], anchor[2], anchor[3]);
	local unit = self.unit or WC_Lib.SearchThingInAdventureByID(self.idUnit, 2, currentAddon);

	GameTooltip:AddLine(unit.name, 1, 1, 1);
	GameTooltip:AddDoubleLine(core.L["Points de vie"]..core.L["2points"].."|cffffffff"..unit.pdvMax.."|r", core.L["Points d'attaque"]..core.L["2points"].."|cffffffff"..unit.damage.."|r");

	-- STATE --
	local state = "";
	if IsInvulMobsFight[self.pos] > 0 then
		state = state.."|T135893:16|t "..core.L["Invulnérable"].." ("..IsInvulMobsFight[self.pos]..") ";
	end
	if IsStunMobsFight[self.pos] > 0 then
		state = state.."|T135860:16|t |cffff0000"..core.L["Étourdi"].." ("..IsStunMobsFight[self.pos]..")|r ";
	end
	if IsSilenceMobsFight[self.pos] > 0 then
		state = state.."|T135975:16|t |cffc04bba"..core.L["Silence"].." ("..IsSilenceMobsFight[self.pos]..")|r ";
	end
	GameTooltip:AddLine(state);
	
	-- SPELLS
	local firstSpell  = true;
	for i = 1, #unit.spells do
		local spell = WC_Lib.SearchThingInAdventureByID(unit.spells[i], 3, currentAddon);
		GameTooltip:AddLine(" ");
		if firstSpell == true then
			GameTooltip:AddLine(core.L["Sort(s)"]);
			firstSpell = false;
		end
		
		GameTooltip:AddLine(spell.name, 1, 1, 1);
		if (spell.isPassive == true) then
			GameTooltip:AddLine(spell.desc.."\n"..core.L["Passif"], 1, 0.82, 0, true);
		elseif (spell.cooldown == 0) then
			GameTooltip:AddLine(spell.desc.."\n"..core.L["Sort de base"], 1, 0.82, 0, true);
		else
			local colorCD = "cffffffff";
			if CdSpellMobsFight[self.pos][i].cooldown <= 0 then
				colorCD = "cff00ff00";
			end
			GameTooltip:AddLine(spell.desc.."\n|"..colorCD..CdSpellMobsFight[self.pos][i].cooldown.." "..core.L["tour(s) restant(s)"].."|r", 1, 0.82, 0, true);
		end
		GameTooltip:AddTexture(spell.icon, {width = 32, height = 32});
	end
	
	-- EFFECTS
	local firstEffect = true;
	for i, v in ipairs(EffectMobsFight[self.pos]) do
		local effect = v;
		if not effect.attributes.isHidden then
			GameTooltip:AddLine(" ");
			if firstEffect == true then
				GameTooltip:AddLine(core.L["Effects"]);
				firstEffect = false;
			end
			if (effect.attributes.isPositive == true) then
				GameTooltip:AddLine(effect.name, 0, 1, 0);
			else
				GameTooltip:AddLine(effect.name, 1, 0, 0);
			end
			local displayPhrase = effect.desc;
			if (effect.attributes.chargeMax > 0 and effect.charge ~= nil) then
				displayPhrase = displayPhrase.."\n|cffffffff"..effect.charge.." "..core.L["charge(s)"];
			end
			if (effect.duration > 0) then
				displayPhrase = displayPhrase.."\n|cffffffff"..effect.duration.." "..core.L["tour(s) restant(s)"].."|r";
			end
			GameTooltip:AddLine(displayPhrase, 1, 0.82, 0, true);
			GameTooltip:AddTexture(effect.icon, {width = 32, height = 32});
		end
	end
	GameTooltip:Show();
end

OnEnterEffectPlayerAdventureFight = function(self, motion)
	GameTooltip:SetOwner(self, "ANCHOR_TOP");
	currentShowTooltip = 6;
	GameTooltip:AddLine(core.L["Effects"]);
	local noVisibleEffect = true;
	local firstEffect = true;
	for i, v in ipairs(EffectMobsFight[6]) do
		local effect = v;
		if not effect.attributes.isHidden then
			if (effect.attributes.isPositive == true) then
				GameTooltip:AddLine(effect.name, 0, 1, 0);
			else
				GameTooltip:AddLine(effect.name, 1, 0, 0);
			end
			local displayPhrase = effect.desc;
			if (effect.charge ~= nil and effect.attributes.chargeMax > 0) then
				displayPhrase = displayPhrase.."\n|cffffffff"..effect.charge.." "..core.L["charge(s)"];
			end
			if (effect.duration > 0) then
				displayPhrase = displayPhrase.."\n|cffffffff"..effect.duration.." "..core.L["tour(s) restant(s)"].."|r";
			end
			GameTooltip:AddLine(displayPhrase, 1, 0.82, 0, true);
			GameTooltip:AddTexture(effect.icon, {width = 32, height = 32});
			noVisibleEffect = false;
		end
	end
	if noVisibleEffect then
		GameTooltip:AddLine(core.L["Vous n'avez aucun effet pour l'instant."], 0.6, 0.6, 0.6);
	end
	GameTooltip:Show();
end

local function refreshCurrentShowTooltip()
	if (currentShowTooltip ~= 0) then
		if (currentShowTooltip == 6) then
			OnEnterEffectPlayerAdventureFight(_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.effectIcon);
		else
			OnEnterTooltipEnnemyAdventureFight(_G["WC_AdventureFightScene"].TooltipScene[currentShowTooltip]);
		end
	end
end

local OnEnterEnnemyScene = function(self, motion)
	if IsTargetable(self.position) and selectedSpell ~= 0 then--selectedSpell ~= 0 and HasMob(self.position) and IsTargetable(self.position) and not IsDead(self.position) then
		_G["WC_AdventureFightScene"].TooltipScene[self.position]:Show();
		_G["WC_AdventureFightScene"].TooltipScene[self.position]:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/bg_tooltipEnnemy",
							 edgeFile = "", 
							 tile = false, edgeSize = 16,
							 insets = { left = -15, right = -15, top = 0, bottom = -6 }});
	end
end
local OnLeaveEnnemyScene = function(self, motion)
	_G["WC_AdventureFightScene"].TooltipScene[self.position]:SetBackdrop({bgFile = "",
						 edgeFile = "", 
						 tile = false, edgeSize = 16,
						 insets = { left = -15, right = -15, top = 0, bottom = -6 }});
end

local function GetNbEffectPlayer()
	local ret = 0;
	for i = 1, TableLength(EffectMobsFight[6]) do
		if not EffectMobsFight[6][i].attributes.isHidden then
			ret = ret + 1;
		end
	end
	return ret;
end

local function GetEffectOnUnitByID(pos, id)
	for i, v in ipairs(EffectMobsFight[pos]) do
		local effect = v;
		if effect.id == id then
			return effect;
		end
	end
	return nil;
end
local function GetSpellOnUnitByID(pos, id)
	for j = 1, #CurrMobsFight[pos].spells do
		if CurrMobsFight[pos].spells[j] == id then
			return WC_Lib.SearchThingInAdventureByID(CurrMobsFight[pos].spells[j], 3, currentAddon);
		end
	end
	return nil;
end

local function Split(s, delimiter)
    result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end

local function CanTriggerEvent(idEvent, posEvent, Event, posUnitHasEvent)
	-- Event.params[1] = position ; -- Event.params[2] = action
	
	-- get linked effect/spell
	local linkedEffect = GetEffectOnUnitByID(posUnitHasEvent, Event.id);
	local linkedSpell  = GetSpellOnUnitByID(posUnitHasEvent, Event.id);
	if not linkedEffect and not linkedSpell then
		return false;
	end
	
	-- CONTINUER LA PHASE 2 DU BOSS 3
	--if CurrMobsFight[posUnitHasEvent] == 0 then return false end
	
	-- check if dead
	if PdvMobsFight[posUnitHasEvent] <= 0 then
		if linkedEffect then
			if not linkedEffect.attributes.activeInDeath then
				return false;
			end
		end
		if linkedSpell then
			if not linkedSpell.attributes.useInDeath then
				return false;
			end
		end
	end
	-- check if stun
	if IsStunMobsFight[posUnitHasEvent] > 0 then
		if linkedEffect then
			if not linkedEffect.attributes.activeInStun then
				return false;
			end
		end
		if linkedSpell then
			if not linkedSpell.attributes.useInStun then
				return false;
			end
		end
	end
	-- check if silence
	if IsSilenceMobsFight[posUnitHasEvent] > 0 then
		if linkedSpell then
			if not linkedSpell.attributes.useInSilence then
				return false;
			end
		end
	end

	if idEvent == "endturn" or idEvent == "beginfight" or idEvent == "eventCalled" then
		return true;
	end
	
	if Event.event == "MOB_ACTION" and idEvent == Event.params[2] then
		if Event.params[1] == "LEFT" then
			if tonumber(posEvent) == 1 then
				return true;
			end
		elseif Event.params[1] == "MIDLEFT" then
			if tonumber(posEvent) == 2 then
				return true;
			end
		elseif Event.params[1] == "MIDDLE" then
			if tonumber(posEvent) == 3 then
				return true;
			end
		elseif Event.params[1] == "MIDRIGHT" then
			if tonumber(posEvent) == 4 then
				return true;
			end
		elseif Event.params[1] == "RIGHT" then
			if tonumber(posEvent) == 5 then
				return true;
			end
		elseif Event.params[1] == "PLAYER" then
			if tonumber(posEvent) == 6 then
				return true;
			end
		-- elseif Event.params[1] == "SIDEBYSIDE" then
			-- if (tonumber(posEvent) == tonumber(posUnitHasEvent) - 1 or tonumber(posEvent) == tonumber(posUnitHasEvent) + 1) and
				-- tonumber(posEvent) ~= 6 then
				-- return true;
			-- end
		elseif Event.params[1] == "SELFLEFT" then
			if tonumber(posEvent) == tonumber(posUnitHasEvent) - 1 then
				return true;
			end
		elseif Event.params[1] == "SELFRIGHT" then
			if tonumber(posEvent) == tonumber(posUnitHasEvent) + 1 and tonumber(posEvent) ~= 6 then
				return true;
			end
		elseif Event.params[1] == "ANYONE" then
			if tonumber(posEvent) >= 1 and tonumber(posEvent) <= 6 then
				return true;
			end
		elseif Event.params[1] == "ENNEMY_PLACE" or Event.params[1] == "ENNEMY_PLAYER" then
			if tonumber(posEvent) >= 1 and tonumber(posEvent) <= 5 then
				return true;
			end
		elseif Event.params[1] == "SELF" then
			if tonumber(posEvent) == tonumber(posUnitHasEvent) then
				return true;
			end
		end
	end
	
	return false;
end

local function EventFight(idEvent)
	local e = Split(idEvent, ":");
	for pos = 1, 6 do
		for i = #ListEventsSpells[pos], 1, -1 do
			for k = 1, #ListEventsSpells[pos][i] do
				if e[2] == "CUSTOM" and ListEventsSpells[pos][i][k].event == "EVENT_CALLED" and ListEventsSpells[pos][i][k].params[1] == e[1] then
					local spell = WC_Lib.SearchThingInAdventureByID(ListEventsSpells[pos][i][k].id, 3, currentAddon);
					if CheckConditionsTrigger(spell.triggers.conditions, spell.id, pos, false) then
						table.insert(currentCasting, {pos = pos, idSpell = spell.id});
						ActionSpell(spell.id, spell.triggers.actions, 1, true, false, pos);
					end
				elseif ListEventsSpells[pos][i][k].event == "EFFECT_ACTION" and tonumber(e[3]) == pos
					and ListEventsSpells[pos][i][k].params[1] == e[1] and ListEventsSpells[pos][i][k].id == e[2] then
					local effect = WC_Lib.SearchThingInAdventureByID(ListEventsSpells[pos][i][k].id, 3, currentAddon);
					if CheckConditionsTrigger(effect.triggers.conditions, effect.id, pos, false) then
						table.insert(currentCasting, {pos = pos, idSpell = effect.id});
						ActionSpell(effect.id, effect.triggers.actions, 1, true, false, pos);
					end
				else
					if ListEventsSpells[pos][i][k].event == "MOB_ACTION" and CanTriggerEvent(e[1], e[2], ListEventsSpells[pos][i][k], pos) then
						local spell = WC_Lib.SearchThingInAdventureByID(ListEventsSpells[pos][i][k].id, 3, currentAddon);
						if CheckConditionsTrigger(spell.triggers.conditions, spell.id, pos, false) then
							table.insert(currentCasting, {pos = pos, idSpell = spell.id});
							ActionSpell(spell.id, spell.triggers.actions, 1, true, false, pos);
						end
					end
				end
			end
		end
	end
end

local function MinusOneSpell()
	-- MINUS 1 CD SPELL --
	for j = 1, 6 do
		for iLapSpell = 1, #CdSpellMobsFight[j] do
			if HasMob(j) and not IsDead(j) then
				if (CdSpellMobsFight[j][iLapSpell].cooldown > 0) then
					CdSpellMobsFight[j][iLapSpell].cooldown = CdSpellMobsFight[j][iLapSpell].cooldown - 1;
				end
			end
		end
	end
	RefreshFrameSpellsPlayer();
end

local function MinusOneEffectAI()
	-- MINUS 1 CD ENNEMIES EFFECT --
	for j = 1, 6 do
		for i = #EffectMobsFight[j], 1, -1 do
			if EffectMobsFight[j][i] and EffectMobsFight[j][i].attributes.duration > 0 then
				EffectMobsFight[j][i].duration = EffectMobsFight[j][i].duration - 1;
				if EffectMobsFight[j][i].duration <= 0 then
					RemoveEffectOnUnit(j, 1, EffectMobsFight[j][i].id);
				end
			end
		end
	end
	for i = 1, #IsStunMobsFight do
		if IsStunMobsFight[i] > 0 then
			SetStateOnUnit("STUN", i, IsStunMobsFight[i] - 1);
		end
	end
	for i = 1, #IsInvulMobsFight do
		if IsInvulMobsFight[i] > 0 then
			SetStateOnUnit("INVUL", i, IsInvulMobsFight[i] - 1);
		end
	end
	for i = 1, #IsSilenceMobsFight do
		if IsSilenceMobsFight[i] > 0 then
			SetStateOnUnit("SILENCE", i, IsSilenceMobsFight[i] - 1);
		end
	end
	_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.effectText:SetText(GetNbEffectPlayer());
end

local function randomByEnnemy()
	local i = 0;
	local limit = 0;
	while (i == 0) do
		limit = limit + 1;
		local randVar = math.random(1, 5);
		if (CurrMobsFight[randVar] ~= 0 and PdvMobsFight[randVar] > 0) then --DANS LES CONDITIONS DES TRIGGERS => and PdvMobsFight[randVar] > 0 and CurrMobsFight[randVar].typeUnit ~= "object") then
			i = 1;
			return randVar;
		end
		if limit > 500 then
			i = 1;
		end
	end
end

local function randomByEnnemyDeadOrEmpty(exception)
	local i = 0;
	local limit = 0;
	while (i == 0) do
		limit = limit + 1;
		local tmp = math.random(1, 5)
		if ((PdvMobsFight[tmp] == "nil" or PdvMobsFight[tmp] <= 0) and exception ~= tmp) then
			i = 1;
			return tmp;
		end
		if limit > 500 then
			i = 1;
		end
	end
end

local function getWaitingInActions(actions)
	local ret = 0;
	for i = 1, #actions do
		if actions[i].mainParam == "WAIT" then
			ret = ret + tonumber(actions[i].params[1]);
		end
	end
	return ret;
end

local function BeginFightEvents()
	local second = 0;
	for pos = 1, 6 do
		for i = #ListEventsSpells[pos], 1, -1 do
			for k = 1, #ListEventsSpells[pos][i] do
				if ListEventsSpells[pos][i][k].event == "BEGIN_FIGHT" and CanTriggerEvent("beginfight", pos, ListEventsSpells[pos][i][k], pos) then
					local spell = WC_Lib.SearchThingInAdventureByID(ListEventsSpells[pos][i][k].id, 3, currentAddon);
					C_Timer.After(second, function ()
						if CheckConditionsTrigger(spell.triggers.conditions, spell.id, pos, false) then
							table.insert(currentCasting, {pos = pos, idSpell = spell.id});
							ActionSpell(spell.id, spell.triggers.actions, 1, true, true, pos);
						end
					end);
					if CheckConditionsTrigger(spell.triggers.conditions, spell.id, pos, false) then
						second = second + getWaitingInActions(spell.triggers.actions) + 1;
					end
				end
			end
		end
	end
	C_Timer.After(second, function ()
		refreshCurrentShowTooltip();
		canPlay = true;
	end);
end

local function EndTurnEvents()
	local second = 0;
	for pos = 1, 6 do
		for i = #ListEventsSpells[pos], 1, -1 do
			for k = 1, #ListEventsSpells[pos][i] do
				if ListEventsSpells[pos][i][k].event == "ENDTURN" and CanTriggerEvent("endturn", pos, ListEventsSpells[pos][i][k], pos) then
					local spell = WC_Lib.SearchThingInAdventureByID(ListEventsSpells[pos][i][k].id, 3, currentAddon);
					C_Timer.After(second, function ()
						if CheckConditionsTrigger(spell.triggers.conditions, spell.id, pos, false) then
							table.insert(currentCasting, {pos = pos, idSpell = spell.id});
							ActionSpell(spell.id, spell.triggers.actions, 1, true, true, pos);
						end
					end);
					if CheckConditionsTrigger(spell.triggers.conditions, spell.id, pos, false) then
						second = second + getWaitingInActions(spell.triggers.actions) + 1;
					end
				end
			end
		end
	end
	C_Timer.After(second, function ()
		MinusOneEffectAI();
		MinusOneSpell();
		JustSummoned = {false, false, false, false, false, false};
		refreshCurrentShowTooltip();
		if IsStunMobsFight[6] > 0 then
			NextTurn();
		else
			canPlay = true;
		end
	end);
end

local function checkSameEffect(unitEffects, id)
	for i, v in ipairs(unitEffects) do
		if (v.id == id) then
			return i;
		end
	end
	return 0;
end

local function AddEffectOnUnit(pos, effectId)
	local effect = WC_Lib.SearchThingInAdventureByID(effectId, 3, currentAddon);
	if not effect or not effect.isEffect then return end
	
	local tmpEffect = {
		id         = effect.id,
		icon       = effect.icon,
		name       = effect.name,
		desc       = effect.desc,
		attributes = effect.attributes,
		triggers   = effect.triggers,
		-- dynamic values
		charge     = 0,
		duration   = effect.attributes.duration
	};
	
	local res = checkSameEffect(EffectMobsFight[pos], effectId);
	if (res ~= 0) then -- SAME EFFECT IN UNIT
		EffectMobsFight[pos][res].duration = effect.attributes.duration;
		if (effect.attributes.chargeMax > 0 and EffectMobsFight[pos][res].charge + 1 <= effect.attributes.chargeMax) then
			EffectMobsFight[pos][res].charge = EffectMobsFight[pos][res].charge + 1;
			EventFight("EFFECT_ACTION_GAIN_STACK:"..effectId..":"..pos);
			EventFight("GAIN_STACK:"..pos);
		end
		if EffectMobsFight[pos][res].charge >= effect.attributes.chargeMax then
			EventFight("EFFECT_ACTION_MAX_STACK:"..effectId..":"..pos);
		end
	else -- NEW EFFECT IN UNIT
		tmpEffect.charge = 1;
		table.insert(EffectMobsFight[pos], tmpEffect);
		local tmpListEvent = {};
		for j = 1, #effect.triggers.events do
			if effect.triggers.events[j].active == nil or effect.triggers.events[j].active == true then
				local infoEvent = {
					id      = effect.id,
					event   = effect.triggers.events[j].mainParam;
					params  = effect.triggers.events[j].params;
				}
				table.insert(tmpListEvent, infoEvent);
			end
		end
		table.insert(ListEventsSpells[pos], tmpListEvent);
		EventFight("EFFECT_ACTION_GAIN_STACK:"..effectId..":"..pos);
		EventFight("GAIN_EFFECT:"..pos);
		if effect.attributes.chargeMax == 1 then
			EventFight("EFFECT_ACTION_MAX_STACK:"..effectId..":"..pos);
		end
	end
	_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.effectText:SetText(GetNbEffectPlayer());
end

function RemoveEffectOnUnit(pos, nbMinus, idEffect)
	local indexRemove = 0;
	for i = 1, TableLength(EffectMobsFight[pos]) do
		local currEffect = EffectMobsFight[pos][i];
		if (currEffect ~= nil and currEffect.id == idEffect) then
			currEffect.charge = currEffect.charge - tonumber(nbMinus);
			EventFight("EFFECT_ACTION_LOSE_STACK:"..idEffect..":"..pos);
			EventFight("LOSE_STACK:"..pos);
			if (currEffect.charge <= 0) then
				indexRemove = i;
			end
		end
	end
	if indexRemove ~= 0 then
		table.remove(EffectMobsFight[pos], indexRemove);
		EventFight("LOSE_EFFECT:"..pos);
		EventFight("EFFECT_ACTION_REMOVE:"..idEffect..":"..pos);
		-- remove event lié à cet effect
		for j = TableLength(ListEventsSpells[pos]), 1, -1 do
			for k = TableLength(ListEventsSpells[pos][j]), 1, -1 do
				if idEffect == ListEventsSpells[pos][j][k].id then
					table.remove(ListEventsSpells[pos][j], k);
				end
			end
		end
	end
	if pos == 6 then
		_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.effectText:SetText(GetNbEffectPlayer());
	end
end

local function RemoveEffectOnUnitOnDeath(pos)
	for i = 1, TableLength(EffectMobsFight[pos]) do
		local currEffect = EffectMobsFight[pos][i];
		if currEffect and not currEffect.attributes.activeInDeath then
			RemoveEffectOnUnit(pos, 9999, currEffect.id)
		end
	end
end

local function IsUnitCasting(pos)
	for i = 1, #currentCasting do
		if currentCasting[i].pos == pos then
			return true;
		end
	end
	return false;
end

local function getPosCastingByIdSpell(id)
	for i = 1, #currentCasting do
		if currentCasting[i].idSpell == id then
			return tonumber(currentCasting[i].pos);
		end
	end
	return nil;
end

local function removePosCastingByIdSpell(id, pos)
	for i = 1, #currentCasting do
		if currentCasting[i] and currentCasting[i].idSpell == id then
			if pos then
				if currentCasting[i].pos == pos then
					table.remove(currentCasting, i);
					break;
				end
			end
			table.remove(currentCasting, i);
			break;
		end
	end
end

local function getPosId(strId, idSpell, pos, isCond)
	local posCasting = pos or getPosCastingByIdSpell(idSpell);	
	if not posCasting then return {} end
	
	local pos  = nil;
	local pos2 = nil;
	local pos3 = nil;
	local pos4 = nil;
	local pos5 = nil;
	if strId == "LEFT" then
		pos = 1;
	elseif strId == "MIDLEFT" then
		pos = 2;
	elseif strId == "MIDDLE" then
		pos = 3;
	elseif strId == "MIDRIGHT" then
		pos = 4;
	elseif strId == "RIGHT" then
		pos = 5;
	elseif strId == "PLAYER" then
		pos = 6;
	elseif strId == "SELF" then
		pos = posCasting;
	elseif strId == "SELFLEFT" then
		pos = posCasting - 1;
		if pos == 6 then
			pos = 1;
		end
	elseif strId == "SELFRIGHT" then
		pos = posCasting + 1;
		if pos == 6 then
			pos = 5;
		end
	elseif strId == "ANYONE" then
		pos = math.random(1, 6);
	elseif strId == "ENNEMY_PLACE" then
		pos = math.random(1, 5);
	elseif strId == "FREE_ENNEMY_PLACE" then
		pos = randomByEnnemyDeadOrEmpty();
	elseif strId == "ENNEMY_PLAYER" then
		pos = randomByEnnemy();
	elseif strId == "ALL_ENNEMY_PLAYER" then
		pos = 1; pos2 = 2; pos3 = 3;  pos4 = 4;  pos5 = 5;  
	elseif strId == "SAME_PREV" then
		pos  = lastTriggerPos[idSpell][1];
		pos2 = lastTriggerPos[idSpell][2];
		pos3 = lastTriggerPos[idSpell][3];
		pos4 = lastTriggerPos[idSpell][4];
		pos5 = lastTriggerPos[idSpell][5];
	elseif strId == "TARGET" then
		if posCasting == 6 then
			pos = selectedMob;
		else
			pos = 6;
		end
	elseif strId == "TARGET_LEFT" then
		if posCasting == 6 then
			if selectedMob > 1 then
				pos = selectedMob - 1;
			end
		else
			pos = 6;
		end
	elseif strId == "TARGET_RIGHT" then
		if posCasting == 6 then
			if selectedMob < 5 then
				pos = selectedMob + 1;
			end
		else
			pos = 6;
		end
	-- elseif strId == "SIDEBYSIDE" then
		-- pos = posCasting - 1;
		-- pos2 = posCasting + 1;
		-- if pos < 1 then
			-- pos = nil;
		-- end
		-- if pos2 > 5 then
			-- pos2 = nil; -- dont work for player
		-- end
	elseif strId == "ACTION_PLAYER" then
		if isCond then
			return lastTriggerPos[idSpell];
		else
			return {};
		end
	end
	if not isCond then
		lastTriggerPos[idSpell] = {pos, pos2, pos3, pos4, pos5};
	end
	return {pos, pos2, pos3, pos4, pos5};
end

function CheckConditionsTrigger(cond, idSpell, posEvent, posActionPlayer)
	-- [START] CHECK IF SPELL IS OFF
	for i = 1, #ListBanSpells do
		if ListBanSpells[i] == idSpell then
			return false;
		end
	end
	-- [END] CHECK IF SPELL IS OFF	
	if posActionPlayer ~= false then
		posActionPlayer = true;
	end
	local ret = true;
	if cond then
		for i = 1, #cond do
			if cond[i].active == nil or cond[i].active == true then
				if cond[i].mainParam == "SAME_STATE_COND" or cond[i].mainParam == "NOT_SAME_STATE_COND" then
					if cond[i].params[2] == "STUN" then
						local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
						if #positions == 0 then ret = ret and false end
						for _, v in pairs(positions) do
							local ret_cond = IsStunMobsFight[v] > 0;
							if cond[i].mainParam == "NOT_SAME_STATE_COND" then
								ret_cond = not ret_cond;
							end
							if HasMob(v) and ret_cond then
								ret = ret and true;
							else
								ret = ret and false;
							end
						end
					elseif cond[i].params[2] == "INVUL" then
						local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
						if #positions == 0 then ret = ret and false end
						for _, v in pairs(positions) do
							local ret_cond = IsInvulMobsFight[v] > 0;
							if cond[i].mainParam == "NOT_SAME_STATE_COND" then
								ret_cond = not ret_cond;
							end
							if HasMob(v) and ret_cond then
								ret = ret and true;
							else
								ret = ret and false;
							end
						end
					elseif cond[i].params[2] == "SILENCE" then
						local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
						if #positions == 0 then ret = ret and false end
						for _, v in pairs(positions) do
							local ret_cond = IsSilenceMobsFight[v] > 0;
							if cond[i].mainParam == "NOT_SAME_STATE_COND" then
								ret_cond = not ret_cond;
							end
							if HasMob(v) and ret_cond then
								ret = ret and true;
							else
								ret = ret and false;
							end
						end
					elseif cond[i].params[2] == "DEAD" then
						local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
						if #positions == 0 then ret = ret and false end
						for _, v in pairs(positions) do
							local ret_cond = IsDead(v);
							if cond[i].mainParam == "NOT_SAME_STATE_COND" then
								ret_cond = not ret_cond;
							end
							if ret_cond then
								ret = ret and true;
							else
								ret = ret and false;
							end
						end
					elseif cond[i].params[2] == "ALIVE" then
						local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
						if #positions == 0 then ret = ret and false end
						for _, v in pairs(positions) do
							local ret_cond = not IsDead(v);
							if cond[i].mainParam == "NOT_SAME_STATE_COND" then
								ret_cond = not ret_cond;
							end
							if ret_cond then
								ret = ret and true;
							else
								ret = ret and false;
							end
						end
					end
				elseif cond[i].mainParam == "SAME_CHARACTER_COND" then
					local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
					if #positions == 0 then ret = ret and false end
					for _, v in pairs(positions) do
						if HasMob(v) then
							local ret_cond = CurrMobsFight[v].id == cond[i].params[2];
							ret = ret and ret_cond;
						else
							ret = ret and false;
						end
					end
				elseif cond[i].mainParam == "NOT_SAME_CHARACTER_COND" then
					local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
					if #positions == 0 then ret = ret and true end
					for _, v in pairs(positions) do
						if HasMob(v) then
							local ret_cond = CurrMobsFight[v].id ~= cond[i].params[2];
							ret = ret and ret_cond;
						else
							ret = ret and true;
						end
					end
				elseif cond[i].mainParam == "HAS_EFFECT_COND" then
					local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
					if #positions == 0 then ret = ret and false end
					for _, v in pairs(positions) do
						if HasMob(v) then
							local effect = GetEffectOnUnitByID(v, cond[i].params[2]);
							if effect then
								ret = ret and true;
							else
								ret = ret and false;
							end
						else
							ret = ret and false;
						end
					end
				elseif cond[i].mainParam == "NOT_HAS_EFFECT_COND" then
					local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
					if #positions == 0 then ret = ret and true end
					for _, v in pairs(positions) do
						if HasMob(v) then
							local effect = GetEffectOnUnitByID(v, cond[i].params[2]);
							if effect then
								ret = ret and false;
							else
								ret = ret and true;
							end
						else
							ret = ret and true;
						end
					end
				elseif cond[i].mainParam == "SCENE_PLACE_COND" then
					local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
					if #positions == 0 then ret = ret and false end
					local posID = {"SCENE_LEFT","SCENE_MIDLEFT","SCENE_MIDDLE","SCENE_MIDRIGHT","SCENE_RIGHT"};
					for _, v in pairs(positions) do
						if HasMob(v) then
							if posID[v] == cond[i].params[2] then
								ret = ret and true;
							else
								ret = ret and false;
							end
						else
							ret = ret and false;
						end
					end
				elseif cond[i].mainParam == "NOT_SCENE_PLACE_COND" then
					local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
					if #positions == 0 then ret = ret and true end
					local posID = {"SCENE_LEFT","SCENE_MIDLEFT","SCENE_MIDDLE","SCENE_MIDRIGHT","SCENE_RIGHT"};
					for _, v in pairs(positions) do
						if HasMob(v) then
							if posID[v] == cond[i].params[2] then
								ret = ret and false;
							else
								ret = ret and true;
							end
						else
							ret = ret and true;
						end
					end
				elseif cond[i].mainParam == "CHARACTER_LIFE_COND" then
					local positions = getPosId(cond[i].params[1], idSpell, posEvent, posActionPlayer);
					if #positions == 0 then ret = ret and false end
					for _, v in pairs(positions) do
						if HasMob(v) then
							if cond[i].params[2] == "EQUAL" and PdvMobsFight[v] == tonumber(cond[i].params[3]) then
								ret = ret and true;
							elseif cond[i].params[2] == "DIFFERENT" and PdvMobsFight[v] ~= tonumber(cond[i].params[3]) then
								ret = ret and true;
							elseif cond[i].params[2] == "SUPERIOR" and PdvMobsFight[v] > tonumber(cond[i].params[3]) then
								ret = ret and true;
							elseif cond[i].params[2] == "INFERIOR" and PdvMobsFight[v] < tonumber(cond[i].params[3]) then
								ret = ret and true;
							else
								ret = ret and false;
							end
						else
							ret = ret and false;
						end
					end
				end
			end
		end
	end
	return ret;
end

function ActionSpell(idSpell, listActions, iAction, noNextTurn, firstTurn, posEvent)
	if curr_incr_IsInFight ~= incr_IsInFight then return end
	local action = listActions[iAction];
	currentTurnTime = 0;
	if iAction == 1 then
		lastTriggerPos[idSpell] = {};
	end
	if action then
		if (action.active == nil or action.active == true) then
			if action.mainParam == "CALL_EVENT" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					EventFight(action.params[1]..":CUSTOM");
				end
			elseif action.mainParam == "ADD_EFFECT" then
				local positions = getPosId(action.params[3], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							for i = 1, tonumber(action.params[1]) do
								AddEffectOnUnit(v, action.params[2]);
							end
						end
					end
				end
			elseif action.mainParam == "ANIME" then
				local positions = getPosId(action.params[2], idSpell, posEvent);			
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) and not IsDead(v) then
							if action.params[3] then
								AnimBaseMobsFight[v] = action.params[1];
							end
							_G["WC_AdventureFightScene"].ModelScene[v]:SetAnimation(tonumber(action.params[1]));
						end
					end
				end
			elseif action.mainParam == "CHANGE_SKIN" then
				local positions = getPosId(action.params[1], idSpell, posEvent);		
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							_G["WC_AdventureFightScene"].ModelScene[v]:SetDisplayInfo(action.params[2]);
							_G["WC_AdventureFightScene"].ModelScene[v]:EquipItem(WeaponMobsFight[v][1]);
							_G["WC_AdventureFightScene"].ModelScene[v]:EquipItem(WeaponMobsFight[v][2]);
						end
					end
				end
			elseif action.mainParam == "CHANGE_BG" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					_G["WC_AdventureFightScene"]:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/"..action.params[1],
										 edgeFile = "Interface/Tooltips/UI-Tooltip-Border", 
										 tile = false, edgeSize = 12,
										 insets = { left = 3, right = 3, top = 3, bottom = 3 }});
				end
			elseif action.mainParam == "DAMAGE" then
				local positions = getPosId(action.params[2], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) and not IsDead(v) then
							EventFight("BEFORE_ATTACKED:"..v);
							local damage = tonumber(action.params[1]);
							if damage == 0 then
								local myself = getPosCastingByIdSpell(idSpell)
								damage = DamageMobsFight[myself];
							end
							if IsInvulMobsFight[v] == 0 then
								PdvMobsFight[v] = PdvMobsFight[v] - damage;
							end
							_G["WC_AdventureFightScene"].ModelScene[v]:SetAnimation(9);
							if IsDead(v) then
								EventFight("JUST_ATTACKED:"..v);
								PlaySound(CurrMobsFight[v].sounds.death, "sfx", false);
								_G["WC_AdventureFightScene"].ModelScene[v]:SetAnimation(1);
								EventFight("DIED:"..v);
								SetStateOnUnit("STUN", v, 0);
								SetStateOnUnit("INVUL", v, 0);
								SetStateOnUnit("SILENCE", v, 0);
								RemoveEffectOnUnitOnDeath(v);
								if CurrMobsFight[v].isObject == true then
									_G["WC_AdventureFightScene"].ModelScene[v]:SetPosition(0, 100, 0);
								end
							else
								EventFight("JUST_ATTACKED:"..v);
								PlaySound(CurrMobsFight[v].sounds.hit, "sfx", false);
							end
							RefreshTooltipFrame(v);
						end
					end
				end
			elseif action.mainParam == "DEFEAT" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					_G["WC_AdventureFightScene"].FFbtn:Disable();
					canPlay = false;
					incr_IsInFight = incr_IsInFight + 1;
					PlaySound("31750", "sfx", false);
					if DBProfile.skillPoints <= 0 then
						StaticPopup_Show("AdventureDefeatPopupNoSkill");
					else
						StaticPopup_Show("AdventureDefeatPopup");
					end
				end
			elseif action.mainParam == "DECREASE_DAMAGE" then
				local positions = getPosId(action.params[2], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) and not IsDead(v) then
							local bonus = tonumber(action.params[1]);
							if bonus == 0 then
								 bonus = DamageMobsFight[getPosCastingByIdSpell(idSpell)];
							end
							if DamageMobsFight[v] - bonus < 0 then
								DamageMobsFight[v] = 0;
							else
								DamageMobsFight[v] = DamageMobsFight[v] - bonus;
							end
							RefreshTooltipFrame(v);
						end
					end
				end
			elseif action.mainParam == "EQUIP" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) and not IsDead(v) then
							for i = 1, #WeaponMobsFight[v] do
								if WeaponMobsFight[v][i] == 0 or WeaponMobsFight[v][i] == "0" then
									WeaponMobsFight[v][i] = tonumber(action.params[2]);
									break;
								end
							end
							_G["WC_AdventureFightScene"].ModelScene[v]:EquipItem(WeaponMobsFight[v][1]);
							_G["WC_AdventureFightScene"].ModelScene[v]:EquipItem(WeaponMobsFight[v][2]);
						end
					end
				end
			elseif action.mainParam == "UNEQUIP" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) and not IsDead(v) then
							for i = 1, #WeaponMobsFight[v] do
								if WeaponMobsFight[v][i] ~= 0 and WeaponMobsFight[v][i] ~= "0" then
									WeaponMobsFight[v][i] = 0;
									break;
								end
							end
							_G["WC_AdventureFightScene"].ModelScene[v]:SetDisplayInfo(DisplayMobsFight[v]);
							_G["WC_AdventureFightScene"].ModelScene[v]:EquipItem(WeaponMobsFight[v][1]);
							_G["WC_AdventureFightScene"].ModelScene[v]:EquipItem(WeaponMobsFight[v][2]);
						end
					end
				end
			elseif action.mainParam == "INCREASE_CD" then
				local positions = getPosId(action.params[3], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							for iLapSpell = 1, #CdSpellMobsFight[v] do
								if CdSpellMobsFight[v][iLapSpell].id == action.params[2] and not CdSpellMobsFight[v][iLapSpell].isEffect then
									CdSpellMobsFight[v][iLapSpell].cooldown = CdSpellMobsFight[v][iLapSpell].cooldown + tonumber(action.params[1]);
								end
							end
							if v == 6 then
								RefreshFrameSpellsPlayer();
							end
						end
					end
					refreshCurrentShowTooltip();
				end
			elseif action.mainParam == "DECREASE_CD" then
				local positions = getPosId(action.params[3], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							for iLapSpell = 1, #CdSpellMobsFight[v] do
								if CdSpellMobsFight[v][iLapSpell].id == action.params[2] then
									CdSpellMobsFight[v][iLapSpell].cooldown = CdSpellMobsFight[v][iLapSpell].cooldown - tonumber(action.params[1]);
									if CdSpellMobsFight[v][iLapSpell].cooldown < 0 then
										CdSpellMobsFight[v][iLapSpell].cooldown = 0;
									end
								end
							end
							if v == 6 then
								RefreshFrameSpellsPlayer();
							end
						end
					end
					refreshCurrentShowTooltip();
				end
			elseif action.mainParam == "FIRST_PLAN" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						local index = 0;
						for i = 1, #orderFrameLevel do
							if v == orderFrameLevel[i] then
								index = i;
								break;
							end
						end
						if index ~= 0 then
							table.remove(orderFrameLevel, index);
							table.insert(orderFrameLevel, v);
							RefreshFrameLevelModel();
						end
					end
				end
			elseif action.mainParam == "FX" then
				local positions = getPosId(action.params[2], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							_G["WC_AdventureFightScene"].ModelScene[v]:ApplySpellVisualKit(action.params[1], not action.params[3]);
						end
					end
				end
			elseif action.mainParam == "HEAL" then
				local positions = getPosId(action.params[2], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							local bonus = tonumber(action.params[1]);
							if bonus == 0 then
								 bonus = DamageMobsFight[getPosCastingByIdSpell(idSpell)];
							end
							local savePdvMob = PdvMobsFight[v];
							if PdvMobsFight[v] + bonus > tonumber(CurrMobsFight[v].pdvMax) then
								PdvMobsFight[v] = tonumber(CurrMobsFight[v].pdvMax);
							else
								PdvMobsFight[v] = PdvMobsFight[v] + bonus;
							end
							
							if savePdvMob <= 0 and savePdvMob + bonus > 0 then -- is REZ
								_G["WC_AdventureFightScene"].ModelScene[v]:SetAnimation(tonumber(AnimBaseMobsFight[v]));
							end
							
							RefreshTooltipFrame(v);
						end
					end
				end
			elseif action.mainParam == "INCREASE_DAMAGE" then
				local positions = getPosId(action.params[2], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							local bonus = tonumber(action.params[1]);
							if bonus == 0 then
								 bonus = DamageMobsFight[getPosCastingByIdSpell(idSpell)];
							end
							DamageMobsFight[v] = DamageMobsFight[v] + bonus;
							RefreshTooltipFrame(v);
						end
					end
				end
			elseif action.mainParam == "INCREASE_HP" then
				local positions = getPosId(action.params[2], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							local bonus = tonumber(action.params[1]);
							if bonus == 0 then
								 bonus = DamageMobsFight[getPosCastingByIdSpell(idSpell)];
							end
							PdvMobsFight[v] = PdvMobsFight[v] + bonus;
							RefreshTooltipFrame(v);
						end
					end
				end
			elseif action.mainParam == "INVUL" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) and not IsDead(v) then
							SetStateOnUnit("INVUL", v, tonumber(action.params[2]))
							EventFight("JUST_INVUL:"..v);
						end
					end
				end
			elseif action.mainParam == "LAST_PLAN" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						local index = 0;
						for i = 1, #orderFrameLevel do
							if v == orderFrameLevel[i] then
								index = i;
								break;
							end
						end
						if index ~= 0 then
							table.remove(orderFrameLevel, index);
							table.insert(orderFrameLevel, 1, v);
							RefreshFrameLevelModel();
						end
					end
				end
			elseif action.mainParam == "MESSAGE" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					_G["WC_AdventureFightScene"].messageFight.text:SetText(action.params[1]);
					C_Timer.After(tonumber(action.params[2]), function () _G["WC_AdventureFightScene"].messageFight.text:SetText(""); end);
				end
			elseif action.mainParam == "MOVE" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if v ~= 6 and HasMob(v) and not IsDead(v) then -- dont work for player
							local target = v;
							if action.params[2] == "LEFT" then
								target = target - 1;
							elseif action.params[2] == "RIGHT" then
								target = target + 1;
							end
							if target > 0 and target < 6 then
								MoveUnit(v, target, action.params[3]);
							end
						end
					end
				end
			elseif action.mainParam == "REMOVE_CHARACTER" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							CurrMobsFight[v]      = 0;
							DisplayMobsFight[v]   = 0;
							AnimBaseMobsFight[v]  = 0;
							PdvMobsFight[v]       = 0;
							DamageMobsFight[v]    = 0;
							CdSpellMobsFight[v]   = {};
							EffectMobsFight[v]    = {};
							ListEventsSpells[v]   = {};
							WeaponMobsFight[v]    = {0,0};
							SetStateOnUnit("STUN", v, 0);
							SetStateOnUnit("INVUL", v, 0);
							SetStateOnUnit("SILENCE", v, 0);
							JustSummoned[v] = false;
							_G["WC_AdventureFightScene"].ModelScene[v]:Hide();
							_G["WC_AdventureFightScene"].TooltipScene[v].AttackLifeFrame:Hide();
							_G["WC_AdventureFightScene"].TooltipScene[v].unit = nil;
						end
					end
				end
			elseif action.mainParam == "REMOVE_EFFECT" then
				local positions = getPosId(action.params[3], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) then
							RemoveEffectOnUnit(v, action.params[1], action.params[2]);
						end
					end
				end
			elseif action.mainParam == "REMOVE_FX" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						_G["WC_AdventureFightScene"].ModelScene[v]:Hide();
						_G["WC_AdventureFightScene"].ModelScene[v]:Show();
					end
				end
			elseif action.mainParam == "RENVERSE" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) and not IsDead(v) then
							_G["WC_AdventureFightScene"].ModelScene[v]:SetAnimation(121);
							for iLapSpell = 1, #CdSpellMobsFight[v] do
								local spell = WC_Lib.SearchThingInAdventureByID(CdSpellMobsFight[v][iLapSpell].id, 3, currentAddon);
								if not spell.isPassive and spell.cooldown > 0 then
									CdSpellMobsFight[v][iLapSpell].cooldown = CdSpellMobsFight[v][iLapSpell].cooldown + tonumber(action.params[2]);
								end
							end
							if v == 6 then
								RefreshFrameSpellsPlayer();
							end
						end
					end
					refreshCurrentShowTooltip();
				end
			elseif action.mainParam == "RESTART_SPELL" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					local spell = WC_Lib.SearchThingInAdventureByID(idSpell, 3, currentAddon);
					if CheckConditionsTrigger(spell.triggers.conditions, spell.id, posEvent, false) then
						ActionSpell(idSpell, listActions, 1, noNextTurn, firstTurn, posEvent);
						return;
					end
				end
			elseif action.mainParam == "SILENCE" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) and not IsDead(v) then
							SetStateOnUnit("SILENCE", v, tonumber(action.params[2]))
							EventFight("JUST_SILENCED:"..v);
						end
					end
				end
			elseif action.mainParam == "SOUND" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					PlaySound(action.params[1], "sfx", false);
				end
			elseif action.mainParam == "STUN" then
				local positions = getPosId(action.params[1], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if HasMob(v) and not IsDead(v) then
							SetStateOnUnit("STUN", v, tonumber(action.params[2]));
							_G["WC_AdventureFightScene"].ModelScene[v]:SetAnimation(14);
							_G["WC_AdventureFightScene"].ModelScene[v]:ApplySpellVisualKit(33, true);
							EventFight("JUST_STUNNED:"..v);
						end
					end
				end
			elseif action.mainParam == "SUMMON" then
				local positions = getPosId(action.params[2], idSpell, posEvent);
				if CheckConditionsTrigger(action.cond, idSpell, posEvent) then
					for _, v in pairs(positions) do
						if action.params[3] == true or ((not HasMob(v)) or IsDead(v)) then
							local unit = WC_Lib.SearchThingInAdventureByID(action.params[1], 2, currentAddon)
							if unit then
								SummonUnit(v, unit, action.params[4]);
								C_Timer.After(0.1, function () EventFight("JUST_SUMMONED:"..v) end);
								if action.params[5] == true then
									JustSummoned[v] = true;
								end
							end
						end
					end
				end
			elseif action.mainParam == "TURNOFF_SPELL" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					local bFound = false;
					for i = 1, #ListBanSpells do
						if ListBanSpells[i] == action.params[1] then
							bFound = true;
						end
					end
					if not bFound then
						table.insert(ListBanSpells, action.params[1]);
					end
				end
			elseif action.mainParam == "TURNON_SPELL" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					for i = 1, #ListBanSpells do
						if ListBanSpells[i] == action.params[1] then
							table.remove(ListBanSpells, i);
						end
					end
				end
			elseif action.mainParam == "VICTORY" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					canPlay = false;
					incr_IsInFight = incr_IsInFight + 1;
					if currentAddon == "WC" and btnFightSelected["WC"] then
						if not WC_AdventuresData.victories[curr_infoFight.idAdventure] or WC_AdventuresData.victories[curr_infoFight.idAdventure] < btnFightSelected["WC"].index then
							WC_AdventuresData.victories[curr_infoFight.idAdventure] = tonumber(btnFightSelected["WC"].index);
							local adventure = WC_Lib.SearchThingInAdventureByID(curr_infoFight.idAdventure, 1, "WC");
							RefreshListFights(adventure.fights, "WC");
						end
					end
					_G["WC_AdventureFightScene"].FFbtn:Disable();
					PlaySound("118535", "sfx", false);
					StaticPopup_Show("AdventureVictoryPopup");
				end
			elseif action.mainParam == "WAIT" then
				if CheckConditionsTrigger(action.cond, idSpell, posEvent, false) then
					currentTurnTime = tonumber(action.params[1]);
				end
			end
		end
		C_Timer.After(currentTurnTime, function () ActionSpell(idSpell, listActions, iAction + 1, noNextTurn, firstTurn, posEvent) end);
	elseif not noNextTurn then
		C_Timer.After(1, function ()
			removePosCastingByIdSpell(idSpell, posEvent);
			NextTurn();
			-- if getPosCastingByIdSpell(idSpell) == 6 then
				-- _G["WC_AdventureFightScene"].ModelScene[6]:SetRotation(3);
			-- end
		end);
	else
		removePosCastingByIdSpell(idSpell, posEvent);
		if getPosCastingByIdSpell(idSpell, posEvent) == 6 then
			_G["WC_AdventureFightScene"].ModelScene[6]:SetRotation(3);
		end
	end
	if noNextTurn and not firstTurn then
		--C_Timer.After(0.5, function ()
			--canPlay = true;
		--end);
	end
	refreshCurrentShowTooltip();
end

local function CanUseSpell(attributesSpell, i)
	local ret = "";
	if not attributesSpell.useInStun and IsStunMobsFight[i] > 0 then
		ret = core.L["Inutilisable en étant étourdi"];
	end
	if not attributesSpell.useInSilence and IsSilenceMobsFight[i] > 0 then
		ret = core.L["Inutilisable en sous silence"];
	end
	if not attributesSpell.useInDeath and IsDead(i) then
		ret = core.L["Inutilisable en étant mort"];
	end
	if not HasMob(i) then
		ret = "No Character";
	end
	return ret;
end

local function ActionMob()
	local nextTurn = true;
	local pos = currentTurn;
	if not JustSummoned[currentTurn] then
		for i = #CdSpellMobsFight[currentTurn], 1, -1 do
			if CdSpellMobsFight[currentTurn][i].cooldown == 0 and CdSpellMobsFight[currentTurn][i].isPassive ~= true and
				CanUseSpell(CdSpellMobsFight[currentTurn][i].attributes, currentTurn) == "" then
				local spell = WC_Lib.SearchThingInAdventureByID(CdSpellMobsFight[currentTurn][i].id, 3, currentAddon);
				if CheckConditionsTrigger(spell.triggers.conditions, spell.id, currentTurn, false) then
					nextTurn = false;
					CdSpellMobsFight[currentTurn][i].cooldown = spell.cooldown + 1;
					EventFight("CAST_SPELL:"..currentTurn);
					C_Timer.After(currentTurnTime, function ()
							table.insert(currentCasting, {pos = currentTurn, idSpell = spell.id});
							ActionSpell(spell.id, spell.triggers.actions, 1)
					end);
				else
				end
				break;
			end
		end
	end
	if nextTurn then
		NextTurn();
	end
end

local function InteractSpellPlayer(self)
	if IsTargetable(self.position) and selectedSpell ~= 0 then--HasMob(self.position) and IsTargetable(self.position) and not IsDead(self.position) and selectedSpell ~= 0 then
		if not IsUnitCasting(6) or selectedSpell.attributes.useAnytime then
			local spell = selectedSpell;
			selectedMob = self.position;
			if CheckConditionsTrigger(spell.triggers.conditions, spell.id, 6, false) then
				if not spell.attributes.useAnytime and not spell.attributes.canReplay then
					canPlay = false;
				end
				selectedSpell   = 0;
				currentTurnTime = 0;
				EventFight("CAST_SPELL:6");
				if (selectedMob == 1) then
					_G["WC_AdventureFightScene"].ModelScene[6]:SetRotation(3.5);
				elseif (selectedMob == 2) then
					_G["WC_AdventureFightScene"].ModelScene[6]:SetRotation(3.25);
				elseif (selectedMob == 3) then
					_G["WC_AdventureFightScene"].ModelScene[6]:SetRotation(3);
				elseif (selectedMob == 4) then
					_G["WC_AdventureFightScene"].ModelScene[6]:SetRotation(2.5);
				elseif (selectedMob == 5) then
					_G["WC_AdventureFightScene"].ModelScene[6]:SetRotation(2.3);
				end
				C_Timer.After(currentTurnTime, function ()
					table.insert(currentCasting, {pos = 6, idSpell = spell.id});
					ActionSpell(spell.id, spell.triggers.actions, 1, spell.attributes.canReplay or spell.attributes.useAnytime);
				end);
				for i = 1, 999 do
					if not _G[ "WC_FSSpellPlayer"..i] then
						break;
					end
					if _G[ "WC_FSSpellPlayer"..i].selected:IsShown() then
						CdSpellMobsFight[6][i].cooldown = spell.cooldown + 1;
						_G[ "WC_FSSpellPlayer"..i].selected:Hide();
						_G[ "WC_FSSpellPlayer"..i].isTargeting = false;
						break;
					end
				end
			end
			RefreshFrameSpellsPlayer();
		end
	end
end

local function ActionPlayer(self)
	local bGood = false;
	if self.infoSpell.attributes.useAnytime then
		bGood = true;
	else
		bGood = canPlay and not IsUnitCasting(6);
	end
	if bGood then
		local messageUseSpell = CanUseSpell(self.infoSpell.attributes, 6);
		if messageUseSpell ~= "" then
			UIErrorsFrame:AddMessage(messageUseSpell, 1, 0, 0);
			PlaySound("47355", "sfx", true);
			return;
		end
		
		if self.infoSpell.attributes.needTarget then
			if selectedSpell ~= 0 and selectedSpell.id == self.infoSpell.id then
				selectedSpell = 0;
				self.isTargeting = false;
			else
				for i = 1, #CurrMobsFight[6].spells do
					_G[ "WC_FSSpellPlayer"..i].isTargeting = false;
				end
				selectedSpell = self.infoSpell;
				self.isTargeting = true;
			end
			OnEnterSpellAdventure(self);
			PlaySound("83", "sfx", false);
		else
			if CheckConditionsTrigger(self.infoSpell.triggers.conditions, self.infoSpell.id, 6, false) then			
				EventFight("CAST_SPELL:6");
				if not self.infoSpell.attributes.useAnytime and not self.infoSpell.attributes.canReplay then
					canPlay = false;
				end
				selectedSpell   = 0;
				currentTurnTime = 0;
				C_Timer.After(currentTurnTime, function ()
					table.insert(currentCasting, {pos = 6, idSpell = self.infoSpell.id});
					ActionSpell(self.infoSpell.id, self.infoSpell.triggers.actions, 1, self.infoSpell.attributes.canReplay or self.infoSpell.attributes.useAnytime);
				end)
				for i = 1, #CurrMobsFight[6].spells do
					_G[ "WC_FSSpellPlayer"..i].isTargeting = false;
					if self.infoSpell.id == _G[ "WC_FSSpellPlayer"..i].infoSpell.id then
						local spell = WC_Lib.SearchThingInAdventureByID(self.infoSpell.id, 3, currentAddon);
						CdSpellMobsFight[6][i].cooldown = spell.cooldown + 1;
						break
					end
				end
			end
		end
		RefreshFrameSpellsPlayer();
	else
		UIErrorsFrame:AddMessage(core.L["Inutilisable pour le moment"], 1, 0, 0);
		PlaySound("47355", "sfx", true);
	end
end

function SetStateOnUnit(stateId, pos, cd)
	local state = nil;
	
	if stateId == "INVUL" then
		state = IsInvulMobsFight;
	elseif stateId == "STUN" then
		state = IsStunMobsFight;
	elseif stateId == "SILENCE" then
		state = IsSilenceMobsFight;
	end
	if not state then return nil end
	
	state[pos] = cd;
	if pos == 6 then
		RefreshStatesPlayer();
	end
end

function IsTargetable(pos)
	if HasMob(pos) then
		if not CurrMobsFight[pos] or CurrMobsFight[pos].isUntargetable == true then
			return false;
		end
	end
	return true;
end

function IsDead(pos)
	if PdvMobsFight[pos] and PdvMobsFight[pos] > 0 then
		return false;
	end
	return true;
end

function HasMob(pos)
	if not CurrMobsFight[pos] or CurrMobsFight[pos] == 0 then
		return false;
	end
	return true;
end

function NextTurn(firstTurn)
	if curr_incr_IsInFight ~= incr_IsInFight then return end
	selectedMob       = 0;
	--selectedSpell     = 0;
	if currentTurn == 6 then
		currentTurn = 1;
	elseif currentTurn == 0 then
		currentTurn = 6;
	else
		currentTurn = currentTurn + 1;
	end
	
	for i = currentTurn, 6 do
		currentTurn = i;
		if HasMob(i) and not IsDead(i) then
			break;
		end
	end
	
	currentTurnTime = 0.25;
	if currentTurn == 6 then -- is player
		if not firstTurn then
			EndTurnEvents();
		else
			BeginFightEvents();
		end
	else
		C_Timer.After(currentTurnTime, function () ActionMob() end);
	end
end



local function SetPositionModel(i, position, sceneScale)
	local diffScale = 0;
	if sceneScale then
		diffScale = sceneScale - UIParent:GetScale();
	end
	if position.rotation ~= nil then
		_G["WC_AdventureFightScene"].ModelScene[i]:SetPosition(position[1],
			position[2],
			position[3] + diffScale);
		_G["WC_AdventureFightScene"].ModelScene[i]:SetRotation(position.rotation);
	else
		_G["WC_AdventureFightScene"].ModelScene[i]:SetPosition(0, 2.4,	0);
	end
end

local function UpdateFramePosition(position)
	_G["WC_AdventureFightScene"].TooltipScene[currentPositionForSaving].AttackLifeFrame:Hide();
	_G["WC_AdventureFightScene"].ModelScene[currentPositionForSaving]:Hide();
	if _G["WC_AdventureFightScene"].InteractScene[currentPositionForSaving] then
		_G["WC_AdventureFightScene"].InteractScene[currentPositionForSaving]:SetBackdrop({bgFile = ""});
	end								 
	currentPositionForSaving = position;
	_G["WC_AdventureFightScene"].TooltipScene[currentPositionForSaving].AttackLifeFrame:Show();
	_G["WC_AdventureFightScene"].ModelScene[currentPositionForSaving]:Show();
	_G["WC_AdventureFightScene"].positionsFrame.titleCurrentPosition:SetText(core.L["Position"].." "..posName[currentPositionForSaving]);
	if _G["WC_AdventureFightScene"].InteractScene[currentPositionForSaving] then
		_G["WC_AdventureFightScene"].InteractScene[currentPositionForSaving]:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/bgTip"});
	end
	SetPositionModel(currentPositionForSaving, _G["WC_AdventureFightScene"].infoUnit.scene[currentPositionForSaving].position, _G["WC_AdventureFightScene"].infoUnit.scene.UIScale);
	_G["WC_AdventureFightScene"].ModelScene[currentPositionForSaving]:SetAnimation(tonumber(_G["WC_AdventureFightScene"].infoUnit.animBase));
end

function RefreshTooltipFrame(pos)
	-- LIFE FRAME
	local tooltip = _G["WC_AdventureFightScene"].TooltipScene[pos];
	if (PdvMobsFight[pos] < tonumber(CurrMobsFight[pos].pdvMax)) then
		tooltip.AttackLifeFrame.lifeText:SetFontObject("GameFontRedLarge");
	elseif (PdvMobsFight[pos] == tonumber(CurrMobsFight[pos].pdvMax)) then
		tooltip.AttackLifeFrame.lifeText:SetFontObject("GameFontHighlightLarge");
	elseif (PdvMobsFight[pos] > tonumber(CurrMobsFight[pos].pdvMax)) then
		tooltip.AttackLifeFrame.lifeText:SetFontObject("GameFontGreenLarge");
	end
	tooltip.AttackLifeFrame.lifeText:SetText(PdvMobsFight[pos]);
	-- DAMAGE FRAME
	local tooltip = _G["WC_AdventureFightScene"].TooltipScene[pos];
	if (DamageMobsFight[pos] < tonumber(CurrMobsFight[pos].damage)) then
		tooltip.AttackLifeFrame.damageText:SetFontObject("GameFontRedLarge");
	elseif (DamageMobsFight[pos] == tonumber(CurrMobsFight[pos].damage)) then
		tooltip.AttackLifeFrame.damageText:SetFontObject("GameFontHighlightLarge");
	elseif (DamageMobsFight[pos] > tonumber(CurrMobsFight[pos].damage)) then
		tooltip.AttackLifeFrame.damageText:SetFontObject("GameFontGreenLarge");
	end
	tooltip.AttackLifeFrame.damageText:SetText(DamageMobsFight[pos]);
	tooltip.AttackLifeFrame:Show();
end

function MoveUnit(from, to, switch)
	if not switch and CurrMobsFight[to] ~= 0 and PdvMobsFight[to] > 0 then return end
	
	if switch then
		local tmpCurrMobsFight      = CurrMobsFight[to];
		local tmpDisplayMobsFight   = DisplayMobsFight[to];
		local tmpAnimBaseMobsFight  = AnimBaseMobsFight[to];
		local tmpPdvMobsFight       = PdvMobsFight[to];
		local tmpDamageMobsFight    = DamageMobsFight[to];
		local tmpCdSpellMobsFight   = CdSpellMobsFight[to];
		local tmpEffectMobsFight    = EffectMobsFight[to];
		local tmpListEventsSpells   = ListEventsSpells[to];
		local tmpWeaponMobsFight    = WeaponMobsFight[to];
		local tmpIsStunMobsFight    = IsStunMobsFight[to];
		local tmpIsSilenceMobsFight = IsSilenceMobsFight[to];
		local tmpIsInvulMobsFight   = IsInvulMobsFight[to];
		local tmpJustSummoned       = JustSummoned[to];
		
		CurrMobsFight[to]      = CurrMobsFight[from];
		DisplayMobsFight[to]   = DisplayMobsFight[from];
		AnimBaseMobsFight[to]  = AnimBaseMobsFight[from];
		PdvMobsFight[to]       = PdvMobsFight[from];
		DamageMobsFight[to]    = DamageMobsFight[from];
		CdSpellMobsFight[to]   = CdSpellMobsFight[from];
		EffectMobsFight[to]    = EffectMobsFight[from];
		ListEventsSpells[to]   = ListEventsSpells[from];
		WeaponMobsFight[to]    = WeaponMobsFight[from];
		JustSummoned[to]       = JustSummoned[from];
		SetStateOnUnit("STUN", to, IsStunMobsFight[from]);
		SetStateOnUnit("INVUL", to, IsInvulMobsFight[from]);
		SetStateOnUnit("SILENCE", to, IsSilenceMobsFight[from]);
		
		CurrMobsFight[from]      = tmpCurrMobsFight;
		DisplayMobsFight[from]   = tmpDisplayMobsFight;
		AnimBaseMobsFight[from]  = tmpAnimBaseMobsFight;
		PdvMobsFight[from]       = tmpPdvMobsFight;
		DamageMobsFight[from]    = tmpDamageMobsFight;
		CdSpellMobsFight[from]   = tmpCdSpellMobsFight;
		EffectMobsFight[from]    = tmpEffectMobsFight;
		ListEventsSpells[from]   = tmpListEventsSpells;
		WeaponMobsFight[from]    = tmpWeaponMobsFight;
		JustSummoned[from]       = tmpJustSummoned;
		SetStateOnUnit("STUN", from, tmpIsStunMobsFight);
		SetStateOnUnit("INVUL", from, tmpIsInvulMobsFight);
		SetStateOnUnit("SILENCE", from, tmpIsSilenceMobsFight);
	else
		CurrMobsFight[to]     = CurrMobsFight[from];
		DisplayMobsFight[to]  = DisplayMobsFight[from];
		AnimBaseMobsFight[to] = AnimBaseMobsFight[from];
		PdvMobsFight[to]      = PdvMobsFight[from];
		DamageMobsFight[to]   = DamageMobsFight[from];
		CdSpellMobsFight[to]  = CdSpellMobsFight[from];
		EffectMobsFight[to]   = EffectMobsFight[from];
		ListEventsSpells[to]  = ListEventsSpells[from];
		WeaponMobsFight[to]   = WeaponMobsFight[from];
		JustSummoned[to]      = JustSummoned[from];
		SetStateOnUnit("STUN", to, IsStunMobsFight[from]);
		SetStateOnUnit("INVUL", to, IsInvulMobsFight[from]);
		SetStateOnUnit("SILENCE", to, IsSilenceMobsFight[from]);
		
		CurrMobsFight[from]      = 0;
		DisplayMobsFight[from]   = 0;
		AnimBaseMobsFight[from]  = 0;
		PdvMobsFight[from]       = 0;
		DamageMobsFight[from]    = 0;
		CdSpellMobsFight[from]   = {};
		EffectMobsFight[from]    = {};
		ListEventsSpells[from]   = {};
		WeaponMobsFight[from]    = {0,0};
		SetStateOnUnit("STUN", from, 0);
		SetStateOnUnit("INVUL", from, 0);
		SetStateOnUnit("SILENCE", from, 0);
	end

	-- UI --
	if CurrMobsFight[from] ~= 0 then
		SetPositionModel(from, CurrMobsFight[from].scene[from].position, CurrMobsFight[from].scene.UIScale);
		_G["WC_AdventureFightScene"].ModelScene[from]:SetDisplayInfo(DisplayMobsFight[from]);
		_G["WC_AdventureFightScene"].ModelScene[from]:EquipItem(WeaponMobsFight[from][1]);
		_G["WC_AdventureFightScene"].ModelScene[from]:EquipItem(WeaponMobsFight[from][2]);
		if not IsDead(from) then
			_G["WC_AdventureFightScene"].ModelScene[from]:SetAnimation(tonumber(AnimBaseMobsFight[from]));
		else
			_G["WC_AdventureFightScene"].ModelScene[from]:SetAnimation(6);
		end
		_G["WC_AdventureFightScene"].ModelScene[from]:SetScript("OnAnimFinished", function (self)
			if not IsDead(from) then
				if IsStunMobsFight[from] > 0 then
					self:SetAnimation(14);
				else
					self:SetAnimation(tonumber(AnimBaseMobsFight[from]));
				end
			end
		end);
		RefreshTooltipFrame(from);
	else
		_G["WC_AdventureFightScene"].ModelScene[from]:Hide();
		_G["WC_AdventureFightScene"].TooltipScene[from].AttackLifeFrame:Hide();
	end
	_G["WC_AdventureFightScene"].TooltipScene[from].unit = CurrMobsFight[from];
	
	if CurrMobsFight[to] ~= 0 then
		SetPositionModel(to, CurrMobsFight[to].scene[to].position, CurrMobsFight[to].scene.UIScale);
		_G["WC_AdventureFightScene"].ModelScene[to]:Show();
		_G["WC_AdventureFightScene"].ModelScene[to]:SetDisplayInfo(DisplayMobsFight[to]);
		_G["WC_AdventureFightScene"].ModelScene[to]:EquipItem(WeaponMobsFight[to][1]);
		_G["WC_AdventureFightScene"].ModelScene[to]:EquipItem(WeaponMobsFight[to][2]);
		if not IsDead(to) then
			_G["WC_AdventureFightScene"].ModelScene[to]:SetAnimation(tonumber(AnimBaseMobsFight[to]));
		else
			_G["WC_AdventureFightScene"].ModelScene[to]:SetAnimation(6);
		end
		_G["WC_AdventureFightScene"].ModelScene[to]:SetScript("OnAnimFinished", function (self)
			if not IsDead(to) then
				if IsStunMobsFight[to] > 0 then
					self:SetAnimation(14);
				else
					self:SetAnimation(tonumber(AnimBaseMobsFight[to]));
				end
			end
		end);
		RefreshTooltipFrame(to);
	else
		_G["WC_AdventureFightScene"].ModelScene[to]:Hide();
		_G["WC_AdventureFightScene"].TooltipScene[to].AttackLifeFrame:Hide();
	end
	_G["WC_AdventureFightScene"].TooltipScene[to].unit = CurrMobsFight[to];
	EventFight("JUST_MOVED:"..to);
end

function SummonUnit(pos, unit, bKeepState)
	CurrMobsFight[pos]      = unit;
	DisplayMobsFight[pos]   = tonumber(unit.displayId);
	AnimBaseMobsFight[pos]  = tonumber(unit.animBase);
	CdSpellMobsFight[pos]   = {};
	WeaponMobsFight[pos][1] = unit.weapon1;
	WeaponMobsFight[pos][2] = unit.weapon2;
	
	if not bKeepState then
		PdvMobsFight[pos]     = tonumber(unit.pdv);
		DamageMobsFight[pos]  = tonumber(unit.damage);
		EffectMobsFight[pos]  = {};
		ListEventsSpells[pos] = {};
		SetStateOnUnit("STUN", pos, 0);
		SetStateOnUnit("INVUL", pos, 0);
		SetStateOnUnit("SILENCE", pos, 0);
	else
		-- Remove event missing spell
		local indexToRemoveEvent = {};
		for i = 1, #ListEventsSpells[pos] do
			for j = 1, #unit.spells do
				if unit.spells[j] == ListEventsSpells[pos][i].id then
					table.insert(indexToRemoveEvent, i);
				end
			end
			for j = 1, #unit.effects do
				if unit.effects[j] == ListEventsSpells[pos][i].id then
					table.insert(indexToRemoveEvent, i);
				end
			end
		end
		for i = #indexToRemoveEvent, 1, -1 do
			table.remove(ListEventsSpells[pos], i);
		end
		-- END Remove event missing spell
	end
	
	-- CD/EVENTS SPELLS --
	for i = 1, #unit.spells do
		-- CD --
		local idSpell = unit.spells[i];
		local spell   = WC_Lib.SearchThingInAdventureByID(idSpell, 3, currentAddon);
		if spell then
			local info = {
				id = idSpell,
				attributes = spell.attributes,
				cooldown   = spell.cooldown,
				posMob     = i,
				isPassive  = spell.isPassive
			};
			if pos == 6 then
				info.cooldown = 0;
				if _G[ "WC_FSSpellPlayer"..i] then
					_G[ "WC_FSSpellPlayer"..i].isTargeting = false;
				end
			end
			table.insert(CdSpellMobsFight[pos], info);
			-- EVENTS --
			if spell.isPassive then
				local tmpListEvent = {};
				for j = 1, #spell.triggers.events do
					if spell.triggers.events[j].active == nil or spell.triggers.events[j].active == true then
						local infoEvent = {
							id      = idSpell,
							event   = spell.triggers.events[j].mainParam;
							params  = spell.triggers.events[j].params;
						}
						table.insert(tmpListEvent, infoEvent);
					end
				end
				table.insert(ListEventsSpells[pos], tmpListEvent);
			end
		end
	end
	if pos == 6 then
		RefreshFrameSpellsPlayer();
	end
	-- EFFECTS --
	for i = 1, #unit.effects do
		local effect = WC_Lib.SearchThingInAdventureByID(unit.effects[i], 3, currentAddon);
		if effect then
			AddEffectOnUnit(pos, effect.id);
		end
	end
	
	-- UI --
	SetPositionModel(pos, unit.scene[pos].position, unit.scene.UIScale);
	_G["WC_AdventureFightScene"].ModelScene[pos]:Show();
	_G["WC_AdventureFightScene"].ModelScene[pos]:SetDisplayInfo(unit.displayId);
	_G["WC_AdventureFightScene"].ModelScene[pos]:EquipItem(WeaponMobsFight[pos][1]);
	_G["WC_AdventureFightScene"].ModelScene[pos]:EquipItem(WeaponMobsFight[pos][2]);
	if not IsDead(pos) then 
		_G["WC_AdventureFightScene"].ModelScene[pos]:SetAnimation(AnimBaseMobsFight[pos]);
	else
		_G["WC_AdventureFightScene"].ModelScene[pos]:SetAnimation(6);
	end
	_G["WC_AdventureFightScene"].ModelScene[pos]:SetScript("OnAnimFinished", function (self)
		if not IsDead(pos) then
			if IsStunMobsFight[pos] > 0 then
				self:SetAnimation(14);
			else
				self:SetAnimation(tonumber(AnimBaseMobsFight[pos]));
			end
		end
	end);
	_G["WC_AdventureFightScene"].TooltipScene[pos].unit = unit;
	RefreshTooltipFrame(pos);
end

local function CreateBtnSpellPlayer(spell, i)
	local mainFrame = CreateFrame("Button", "WC_FSSpellPlayer"..i, _G["WC_AdventureFightScene"]);
	mainFrame:SetSize(40, 40);
	mainFrame:SetFrameLevel(_G["WC_AdventureFightScene"]:GetFrameLevel() + 20);
	mainFrame.isPlayer = true;
	mainFrame:SetScript("OnClick", ActionPlayer);
	mainFrame:SetScript("OnEnter", OnEnterSpellAdventure);
	mainFrame:SetScript("OnLeave", WC_Lib.OnLeave);
	mainFrame.selected = CreateFrame("Frame", nil, mainFrame, BackdropTemplateMixin and "BackdropTemplate");
	mainFrame.selected:SetSize(mainFrame:GetWidth(), mainFrame:GetHeight()+1);
	mainFrame.selected:SetPoint("CENTER", mainFrame, "CENTER");
	mainFrame.selected:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/CheckButtonHilight"});
	mainFrame.selected:Hide();
	
	mainFrame.cooldownFrame = CreateFrame("Button", nil, mainFrame);
	mainFrame.cooldownFrame:SetSize(40, 40);
	mainFrame.cooldownFrame:SetPoint("CENTER", mainFrame, "CENTER");
	mainFrame.cooldownFrame:SetFrameLevel(mainFrame:GetFrameLevel() + 1);
	mainFrame.cooldownFrame:Hide();
	
	mainFrame.cooldownFrame.bg = mainFrame.cooldownFrame:CreateTexture(nil, "BACKGROUND");
	mainFrame.cooldownFrame.bg:SetAllPoints(true);
	mainFrame.cooldownFrame.bg:SetColorTexture(0, 0, 0, 0.65);
	
	mainFrame.cooldownFrame.text = mainFrame.cooldownFrame:CreateFontString(nil, "OVERLAY", nil, mainFrame.cooldownFrame);
	mainFrame.cooldownFrame.text:SetFontObject("GameFontHighlightLarge");
	mainFrame.cooldownFrame.text:SetSize(mainFrame:GetWidth(), 0);
	mainFrame.cooldownFrame.text:SetText(spell.cooldown);
	mainFrame.cooldownFrame.text:SetPoint("CENTER", mainFrame.cooldownFrame, "CENTER");
		
	if (i == 1) then
		mainFrame:SetPoint("BOTTOM", _G["WC_AdventureFightScene"], "BOTTOM", 150, 50);
	elseif (i%6 == 0) then
		mainFrame:SetPoint("BOTTOM", _G["WC_FSSpellPlayer"..(i - 5)], "TOP", 0, 10);	
	else
		mainFrame:SetPoint("RIGHT", _G["WC_FSSpellPlayer"..(i - 1)], "RIGHT", 50, 0);
	end
	return mainFrame;
end

function RefreshStatesPlayer()
	if IsStunMobsFight[6] > 0 then
		_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.StunState:Show();
	else
		_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.StunState:Hide();
	end
	if IsSilenceMobsFight[6] > 0 then
		_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.SilenceState:Show();
		if _G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.StunState:IsShown() then
			_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.SilenceState:SetPoint("RIGHT", _G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.StunState, "LEFT", -10, 0);
		else
			_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.SilenceState:SetPoint("RIGHT", _G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.lifeText, "LEFT", -10, 0);
		end
	else
		_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.SilenceState:Hide();
	end
	if IsInvulMobsFight[6] > 0 then
		_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.InvulState:Show();
		if _G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.SilenceState:IsShown() then
			_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.InvulState:SetPoint("RIGHT", _G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.SilenceState, "LEFT", -10, 0);
		elseif _G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.StunState:IsShown() then
			_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.InvulState:SetPoint("RIGHT", _G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.StunState, "LEFT", -10, 0);
		else
			_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.InvulState:SetPoint("RIGHT", _G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.lifeText, "LEFT", -10, 0);
		end
	else
		_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame.InvulState:Hide();
	end
end

function RefreshFrameLevelModel()
	for i = 1, #orderFrameLevel do
		_G["WC_AdventureFightScene"].ModelScene[orderFrameLevel[i]]:SetFrameLevel(_G["WC_AdventureFightScene"]:GetFrameLevel() + (i + 3));  -- 9 Max FrameLevel
	end
end

function RefreshFrameSpellsPlayer()
	local k = 0;
	if CurrMobsFight[6] ~= 0 then
		local spells = CurrMobsFight[6].spells;
		for i = 1, #spells do
			local spell = WC_Lib.SearchThingInAdventureByID(spells[i], 3, currentAddon);
			local frameSpell = _G["WC_FSSpellPlayer"..i];
			if not frameSpell then
				frameSpell = CreateBtnSpellPlayer(spell, i);
			end
			if spell.isPassive then
				frameSpell:SetScript("OnClick", nil);
			else
				frameSpell:SetScript("OnClick", ActionPlayer);
			end
			frameSpell:SetNormalTexture(spell.icon);
			frameSpell:SetHighlightTexture(spell.icon);
			frameSpell.infoSpell = spell;
			
			frameSpell.selected:Hide();
			if frameSpell.isTargeting then
				frameSpell.selected:Show();
			end
			if CdSpellMobsFight[6] and CdSpellMobsFight[6][i].cooldown > 0 then
				frameSpell.cooldownFrame:Show();
				frameSpell.cooldownFrame.text:SetText(CdSpellMobsFight[6][i].cooldown);
			else
				frameSpell.cooldownFrame:Hide();
			end
			
			k = i;
			frameSpell:Show();
		end
		_G["WC_AdventureFightScene"].TooltipScene[6].AttackLifeFrame:SetFrameLevel(_G["WC_AdventureFightScene"]:GetFrameLevel() + 11);
	end
	
	-- HIDE LES FRAMES EN TROP
	for k = k + 1, 999 do
		if not _G["WC_FSSpellPlayer"..k] then
			break;
		else
			_G["WC_FSSpellPlayer"..k]:Hide();
		end
	end
end

function ResetFightAdventures()
	curr_incr_IsInFight = incr_IsInFight;
	currentTurn        = 0;
	currentTurnTime    = 0;
	currentCasting     = {};
	lastTriggerPos     = {};
	CurrMobsFight      = {0, 0, 0, 0, 0, 0};
	DisplayMobsFight   = {0, 0, 0, 0, 0, 0};
	AnimBaseMobsFight  = {0, 0, 0, 0, 0, 0};
	WeaponMobsFight    = {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}};
	PdvMobsFight       = {0, 0, 0, 0, 0, 0};
	DamageMobsFight    = {0, 0, 0, 0, 0, 0};
    IsStunMobsFight    = {0, 0, 0, 0, 0, 0};
    IsSilenceMobsFight = {0, 0, 0, 0, 0, 0};
    IsInvulMobsFight   = {0, 0, 0, 0, 0, 0};
	CdSpellMobsFight   = {{}, {}, {}, {}, {}, {}};
	EffectMobsFight    = {{}, {}, {}, {}, {}, {}};
	ListEventsSpells   = {{}, {}, {}, {}, {}, {}};
	ListBanSpells      = {};
	JustSummoned       = {false, false, false, false, false, false};
	orderFrameLevel    = {1,5,2,4,3,6};
	-- PLAYER VALUES --
	selectedSpell = 0;
	selectedMob   = 0;
	canPlay       = false;
	
	for i = 1, #CurrMobsFight do
		_G["WC_AdventureFightScene"].ModelScene[i]:Hide();
		_G["WC_AdventureFightScene"].TooltipScene[i].unit = nil;
		_G["WC_AdventureFightScene"].TooltipScene[i]:Show();
		_G["WC_AdventureFightScene"].TooltipScene[i].AttackLifeFrame:Hide();
		if _G["WC_AdventureFightScene"].InteractScene[i] then
			_G["WC_AdventureFightScene"].InteractScene[i]:SetBackdrop({bgFile = ""});
		end
	end
	RefreshFrameSpellsPlayer();
end

function ShowFightSceneAdventure(infoFight, infoUnit, addon)
	currentAddon = addon;
	_G["BtnActiveWCCreator"]:Disable();
	if _G["BtnInactiveWCCreator"] then
		_G["BtnInactiveWCCreator"]:Disable();
	end
	if not _G["WC_AdventureFightScene"] then
		--_G[addon.."_InfoModelUnitAdventure"]:SetFrameLevel(9910);

		--- FIGHT SCENE ---
		local mainFrame = CreateFrame("Frame", "WC_AdventureFightScene", frameDraggable, BackdropTemplateMixin and "BackdropTemplate");
		mainFrame:SetSize(800,454);
		mainFrame:SetPoint("BOTTOM", frameDraggable, "BOTTOM", 0, 0);
		mainFrame:SetFrameLevel(502);
		mainFrame:EnableMouse(true);
		mainFrame:SetScript("OnHide", function (self)
			if _G["WCC_UnitEditFrames"] then
				_G["WCC_UnitEditFrames"]:Show();
			end
			if (_G[addon.."_InfoModelUnitAdventure"]) then
				_G[addon.."_InfoModelUnitAdventure"]:Show();
			end
			_G["BtnActiveWCCreator"]:Enable();
			if _G["BtnInactiveWCCreator"] then
				_G["BtnInactiveWCCreator"]:Enable();
			end
		end);
		-- mainFrame:SetBackdrop({bgFile = BgFightScene,
								 -- edgeFile = "Interface/Tooltips/UI-Tooltip-Border", 
								 -- tile = false, edgeSize = 12,
								 -- insets = { left = 3, right = 3, top = 3, bottom = 3 }});

	    mainFrame.messageFight = CreateFrame("Frame", nil, mainFrame, BackdropTemplateMixin and "BackdropTemplate");
		mainFrame.messageFight:SetSize(mainFrame:GetWidth() - 20, mainFrame:GetHeight() - 20);
		mainFrame.messageFight:SetPoint("CENTER", mainFrame, "CENTER");
		mainFrame.messageFight:SetFrameLevel(_G["WC_AdventureFightScene"]:GetFrameLevel() + 20);
		mainFrame.messageFight.text = mainFrame.messageFight:CreateFontString(nil, "OVERLAY", nil, mainFrame.messageFight);
		mainFrame.messageFight.text:SetFontObject("GameFontNormalLarge");
		mainFrame.messageFight.text:SetSize(mainFrame.messageFight:GetWidth(), 0);
		mainFrame.messageFight.text:SetPoint("CENTER", mainFrame.messageFight, "CENTER");
		mainFrame.messageFight.text:SetText("");
			
		mainFrame.FFbtn = CreateFrame("Button", nil, mainFrame, "UIPanelButtonTemplate");
		mainFrame.FFbtn:SetSize(90, 30);
		mainFrame.FFbtn:SetText(core.L["Abandonner"]);
		mainFrame.FFbtn:SetPoint("BOTTOMRIGHT", mainFrame, "BOTTOMRIGHT", -5, 5);
		mainFrame.FFbtn:SetFrameLevel(mainFrame:GetFrameLevel() + 20);
		mainFrame.FFbtn:SetScript("OnClick", function(self)
			if self:GetParent().infoUnit then -- POSITION MODE
				_G["WC_AdventureFightScene"]:Hide();
				if _G["WCC_ListBgPicture"] then
					_G["WCC_ListBgPicture"]:Hide();
				end
			else -- FIGHT MODE
				StaticPopup_Show("FFAdventure");
			end
		end);

		mainFrame.ModelScene    = {};
		mainFrame.InteractScene = {};
		mainFrame.TooltipScene  = {};
		for i = 1, 5 do
			-- FIGHT SCENE ENNEMIES --
			local FSEnnemy = CreateFrame("CinematicModel", nil, mainFrame);
			FSEnnemy:SetSize(mainFrame:GetWidth(), mainFrame:GetHeight() - 2);
			FSEnnemy:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 0, 0);
			FSEnnemy:SetRotation(0);
			FSEnnemy.cursorX = 0;
			FSEnnemy.cursorY = 0;
			FSEnnemy.camDistance = 1;
			FSEnnemy:SetCamDistanceScale(1);
			FSEnnemy:EnableMouse(false);
			FSEnnemy:SetScript("OnMouseDown", WC_Lib.ModelOnMouseDown)
			FSEnnemy:SetScript("OnMouseUp", WC_Lib.ModelOnMouseUp)
			FSEnnemy:SetScript("OnMouseWheel", function (self, delta)
				if self:GetParent().infoUnit then
					local z, x, y = self:GetPosition();
					self:SetPosition(z + (0.1 * delta), x, y);
				end
			end);		
			FSEnnemy:SetScript("OnShow", function (self)
				if self:GetParent().infoUnit then
					self:EquipItem(self:GetParent().infoUnit.weapon1);
					self:EquipItem(self:GetParent().infoUnit.weapon2);
				else
					self:EquipItem(WeaponMobsFight[i][1]);
					self:EquipItem(WeaponMobsFight[i][2]);
				end
			end);
			FSEnnemy:Hide();
			
			table.insert(mainFrame.ModelScene, FSEnnemy);
			
			-- INTERACT SCENE ENNEMIES --
			local InteractEnnemy = CreateFrame("Button", nil, mainFrame, BackdropTemplateMixin and "BackdropTemplate");
			InteractEnnemy:SetSize(160,250);
			InteractEnnemy:SetFrameLevel(_G["WC_AdventureFightScene"]:GetFrameLevel() + 10);
			InteractEnnemy:SetBackdrop({bgFile = "",
								 edgeFile = "", 
								 tile = false, edgeSize = 16,
								 insets = { left = 0, right = 3, top = 0, bottom = 0 }});
			if i == 1 then
				InteractEnnemy:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 0, 0);
			else			
				InteractEnnemy:SetPoint("TOPLEFT", mainFrame.InteractScene[i - 1], "TOPRIGHT", 0, 0);
			end
			InteractEnnemy:SetScript("OnEnter", OnEnterEnnemyScene);
			InteractEnnemy:SetScript("OnLeave", OnLeaveEnnemyScene);
			InteractEnnemy.position = i;
			InteractEnnemy:SetScript("OnClick", InteractSpellPlayer);
			table.insert(mainFrame.InteractScene, InteractEnnemy);
			
			-- TOOLTIP SCENE ENNEMIES --
			local TooltipEnnemy = CreateFrame("Frame", nil, InteractEnnemy, BackdropTemplateMixin and "BackdropTemplate");
			TooltipEnnemy:SetSize(120,30);
			TooltipEnnemy:SetPoint("TOP");
			TooltipEnnemy.Anchor = {"ANCHOR_BOTTOM", 0, 0};
			TooltipEnnemy:SetScript("OnLeave", function(self, motion) WC_Lib.OnLeave(); currentShowTooltip = 0 end);
			TooltipEnnemy.pos = i;
			TooltipEnnemy:Hide();
		
			TooltipEnnemy.AttackLifeFrame = CreateFrame("Frame", nil, InteractEnnemy, BackdropTemplateMixin and "BackdropTemplate");
			TooltipEnnemy.AttackLifeFrame:SetSize(120,30);
			TooltipEnnemy.AttackLifeFrame:SetPoint("TOP");
			TooltipEnnemy.AttackLifeFrame:Hide();
		
			TooltipEnnemy.AttackLifeFrame.lifeIcon = CreateFrame("Frame", nil, TooltipEnnemy.AttackLifeFrame, BackdropTemplateMixin and "BackdropTemplate");
			TooltipEnnemy.AttackLifeFrame.lifeIcon:SetSize(16,16);
			TooltipEnnemy.AttackLifeFrame.lifeIcon:SetPoint("CENTER", TooltipEnnemy.AttackLifeFrame, "CENTER", -10, 0);
			TooltipEnnemy.AttackLifeFrame.lifeIcon:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/spells/icon_life",
								 edgeFile = "", 
								 tile = false, edgeSize = 16,
								 insets = { left = 0, right = 3, top = 0, bottom = 0 }});
			TooltipEnnemy.AttackLifeFrame.lifeText = TooltipEnnemy.AttackLifeFrame:CreateFontString(nil, "OVERLAY", nil, TooltipEnnemy.AttackLifeFrame);
			TooltipEnnemy.AttackLifeFrame.lifeText:SetFontObject("GameFontHighlightLarge");
			TooltipEnnemy.AttackLifeFrame.lifeText:SetPoint("RIGHT", TooltipEnnemy.AttackLifeFrame.lifeIcon, "LEFT", -3, 0);
			TooltipEnnemy.AttackLifeFrame.lifeText:SetText("?");
			
			TooltipEnnemy.AttackLifeFrame.damageIcon = CreateFrame("Frame", nil, TooltipEnnemy.AttackLifeFrame, BackdropTemplateMixin and "BackdropTemplate");
			TooltipEnnemy.AttackLifeFrame.damageIcon:SetSize(16,16);
			TooltipEnnemy.AttackLifeFrame.damageIcon:SetPoint("CENTER", TooltipEnnemy.AttackLifeFrame, "CENTER", 10, 0);
			TooltipEnnemy.AttackLifeFrame.damageIcon:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/spells/icon_attack",
								 edgeFile = "", 
								 tile = false, edgeSize = 16,
								 insets = { left = 0, right = 3, top = 0, bottom = 0 }});
			TooltipEnnemy.AttackLifeFrame.damageText = TooltipEnnemy.AttackLifeFrame:CreateFontString(nil, "OVERLAY", nil, TooltipEnnemy.AttackLifeFrame);
			TooltipEnnemy.AttackLifeFrame.damageText:SetFontObject("GameFontHighlightLarge");
			TooltipEnnemy.AttackLifeFrame.damageText:SetPoint("LEFT", TooltipEnnemy.AttackLifeFrame.damageIcon, "RIGHT", 0, 0);
			TooltipEnnemy.AttackLifeFrame.damageText:SetText("?");
			table.insert(mainFrame.TooltipScene, TooltipEnnemy);
		end

		-- FIGHT SCENE PLAYER --
		local FSPlayer = CreateFrame("CinematicModel", nil, mainFrame);
		FSPlayer:SetSize(mainFrame:GetWidth(), mainFrame:GetHeight() - 2);
		FSPlayer:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 0, 0);
		FSPlayer:SetRotation(0);
		FSPlayer.cursorX = 0;
		FSPlayer.cursorY = 0;
		FSPlayer:EnableMouse(false);
		FSPlayer:SetScript("OnMouseDown", WC_Lib.ModelOnMouseDown)
		FSPlayer:SetScript("OnMouseUp", WC_Lib.ModelOnMouseUp)
		FSPlayer:SetScript("OnMouseWheel", function (self, delta)
			local z, x, y = self:GetPosition();
			self:SetPosition(z + (0.1 * delta), x, y);
		end);
		FSPlayer:SetCamDistanceScale(1);
		FSPlayer.camDistance = 1;			
		FSPlayer:SetScript("OnShow", function (self)
			if self:GetParent().infoUnit then
				self:EquipItem(self:GetParent().infoUnit.weapon1);
				self:EquipItem(self:GetParent().infoUnit.weapon2);
			else
				self:EquipItem(WeaponMobsFight[6][1]);
				self:EquipItem(WeaponMobsFight[6][2]);
			end
		end);
		FSPlayer:Hide();
		table.insert(mainFrame.ModelScene, FSPlayer);
		
		-- TOOLTIP SCENE PLAYER --		
		local TooltipPlayer = CreateFrame("Frame", nil, mainFrame);
		TooltipPlayer:SetSize(200,30);
		TooltipPlayer:SetPoint("RIGHT", mainFrame.FFbtn, "LEFT", -5, 0);
		TooltipPlayer:Hide();
		
		TooltipPlayer.AttackLifeFrame = CreateFrame("Frame", nil, mainFrame);
		TooltipPlayer.AttackLifeFrame:SetSize(200,30);
		TooltipPlayer.AttackLifeFrame:SetPoint("RIGHT", mainFrame.FFbtn, "LEFT", -5, 0);
		TooltipPlayer.AttackLifeFrame:Hide();
		
		TooltipPlayer.AttackLifeFrame.effectText = TooltipPlayer.AttackLifeFrame:CreateFontString(nil, "OVERLAY", nil, TooltipPlayer.AttackLifeFrame);
		TooltipPlayer.AttackLifeFrame.effectText:SetFontObject("GameFontHighlightLarge");
		TooltipPlayer.AttackLifeFrame.effectText:SetPoint("RIGHT", TooltipPlayer.AttackLifeFrame, "RIGHT", 0, 0);
		TooltipPlayer.AttackLifeFrame.effectText:SetText(GetNbEffectPlayer());
		
		TooltipPlayer.AttackLifeFrame.effectIcon = CreateFrame("Frame", nil, TooltipPlayer.AttackLifeFrame, BackdropTemplateMixin and "BackdropTemplate");
		TooltipPlayer.AttackLifeFrame.effectIcon:SetSize(24,24);
		TooltipPlayer.AttackLifeFrame.effectIcon:SetPoint("RIGHT", TooltipPlayer.AttackLifeFrame.effectText, "LEFT", 0, 0);
		TooltipPlayer.AttackLifeFrame.effectIcon:SetScript("OnEnter", OnEnterEffectPlayerAdventureFight);
		TooltipPlayer.AttackLifeFrame.effectIcon:SetScript("OnLeave", function(self, motion) WC_Lib.OnLeave(); currentShowTooltip = 0 end);
		TooltipPlayer.AttackLifeFrame.effectIcon:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/spells/icon_effect",
							 edgeFile = "",
							 tile = false, edgeSize = 16,
							 insets = { left = 0, right = 3, top = 0, bottom = 0 }});
		
		TooltipPlayer.AttackLifeFrame.damageText = TooltipPlayer.AttackLifeFrame:CreateFontString(nil, "OVERLAY", nil, TooltipPlayer.AttackLifeFrame);
		TooltipPlayer.AttackLifeFrame.damageText:SetFontObject("GameFontHighlightLarge");
		TooltipPlayer.AttackLifeFrame.damageText:SetPoint("RIGHT", TooltipPlayer.AttackLifeFrame.effectIcon, "LEFT", -5, 0);
		TooltipPlayer.AttackLifeFrame.damageText:SetText("0");
		TooltipPlayer.AttackLifeFrame.damageIcon = CreateFrame("Frame", nil, TooltipPlayer.AttackLifeFrame, BackdropTemplateMixin and "BackdropTemplate");
		TooltipPlayer.AttackLifeFrame.damageIcon:SetSize(20,20);
		TooltipPlayer.AttackLifeFrame.damageIcon:SetPoint("RIGHT", TooltipPlayer.AttackLifeFrame.damageText, "LEFT", 0, 0);
		TooltipPlayer.AttackLifeFrame.damageIcon:SetScript("OnEnter", function(self)
			if CurrMobsFight[6] ~= 0 then
				GameTooltip:SetOwner(self, "ANCHOR_TOP");
				GameTooltip:AddLine(DamageMobsFight[6].."/"..CurrMobsFight[6].damage);
				GameTooltip:Show();
			end
		end);
		TooltipPlayer.AttackLifeFrame.damageIcon:SetScript("OnLeave", WC_Lib.OnLeave);
		TooltipPlayer.AttackLifeFrame.damageIcon:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/spells/icon_attack",
							 edgeFile = "", 
							 tile = false, edgeSize = 16,
							 insets = { left = 0, right = 3, top = 0, bottom = 0 }});
		
		TooltipPlayer.AttackLifeFrame.lifeIcon = CreateFrame("Frame", nil, TooltipPlayer.AttackLifeFrame, BackdropTemplateMixin and "BackdropTemplate");
		TooltipPlayer.AttackLifeFrame.lifeIcon:SetSize(24,24);
		TooltipPlayer.AttackLifeFrame.lifeIcon:SetPoint("RIGHT", TooltipPlayer.AttackLifeFrame.damageIcon, "LEFT", -5, 0);
		TooltipPlayer.AttackLifeFrame.lifeIcon:SetScript("OnLeave", WC_Lib.OnLeave);
		TooltipPlayer.AttackLifeFrame.lifeIcon:SetScript("OnEnter", function(self)
			GameTooltip:SetOwner(self, "ANCHOR_TOP");
			if CurrMobsFight[6] ~= 0 then
				GameTooltip:AddLine(PdvMobsFight[6].."/"..CurrMobsFight[6].pdvMax);
				GameTooltip:Show();
			end
		end);
		TooltipPlayer.AttackLifeFrame.lifeIcon:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/spells/icon_life",
							 edgeFile = "", 
							 tile = false, edgeSize = 16,
							 insets = { left = 0, right = 3, top = 0, bottom = 0 }});
		TooltipPlayer.AttackLifeFrame.lifeText = TooltipPlayer.AttackLifeFrame:CreateFontString(nil, "OVERLAY", nil, TooltipPlayer.AttackLifeFrame);
		TooltipPlayer.AttackLifeFrame.lifeText:SetFontObject("GameFontHighlightLarge");
		TooltipPlayer.AttackLifeFrame.lifeText:SetPoint("RIGHT", TooltipPlayer.AttackLifeFrame.lifeIcon, "RIGHT", -30, 0);
		TooltipPlayer.AttackLifeFrame.lifeText:SetText("0");

		table.insert(mainFrame.TooltipScene, TooltipPlayer);
		
		-- STATE FRAME --
		-- INVUL
		TooltipPlayer.AttackLifeFrame.InvulState = CreateFrame("Button", nil, TooltipPlayer.AttackLifeFrame);
		TooltipPlayer.AttackLifeFrame.InvulState:SetSize(24, 24);
		TooltipPlayer.AttackLifeFrame.InvulState:SetPoint("RIGHT", TooltipPlayer.AttackLifeFrame.lifeText, "LEFT", -5, 0);
		TooltipPlayer.AttackLifeFrame.InvulState:SetNormalTexture(135893);
		--TooltipPlayer.AttackLifeFrame.InvulState:SetFrameLevel(TooltipPlayer:GetFrameLevel() + 4);
		TooltipPlayer.AttackLifeFrame.InvulState:Hide();
		TooltipPlayer.AttackLifeFrame.InvulState:SetScript("OnLeave", WC_Lib.OnLeave);
		TooltipPlayer.AttackLifeFrame.InvulState:SetScript("OnEnter", function(self) 
			GameTooltip:SetOwner(self, "ANCHOR_TOP");
			GameTooltip:AddLine(core.L["Invulnérable"].." ("..IsInvulMobsFight[6]..")");
			GameTooltip:Show();
		end);
		-- STUN
		TooltipPlayer.AttackLifeFrame.StunState = CreateFrame("Button", nil, TooltipPlayer.AttackLifeFrame);
		TooltipPlayer.AttackLifeFrame.StunState:SetSize(24, 24);
		TooltipPlayer.AttackLifeFrame.StunState:SetPoint("RIGHT", TooltipPlayer.AttackLifeFrame.lifeText, "LEFT", -5, 0);
		TooltipPlayer.AttackLifeFrame.StunState:SetNormalTexture(135860);
		--TooltipPlayer.AttackLifeFrame.StunState:SetFrameLevel(TooltipPlayer:GetFrameLevel() + 4);
		TooltipPlayer.AttackLifeFrame.StunState:Hide();
		TooltipPlayer.AttackLifeFrame.StunState:SetScript("OnLeave", WC_Lib.OnLeave);
		TooltipPlayer.AttackLifeFrame.StunState:SetScript("OnEnter", function(self) 
			GameTooltip:SetOwner(self, "ANCHOR_TOP");
			GameTooltip:AddLine("|cffff0000"..core.L["Étourdi"].." ("..IsStunMobsFight[6]..")|r");
			GameTooltip:Show();
		end);
		-- SILENCE
		TooltipPlayer.AttackLifeFrame.SilenceState = CreateFrame("Button", nil, TooltipPlayer.AttackLifeFrame);
		TooltipPlayer.AttackLifeFrame.SilenceState:SetSize(24, 24);
		TooltipPlayer.AttackLifeFrame.SilenceState:SetPoint("RIGHT", TooltipPlayer.AttackLifeFrame.lifeText, "LEFT", -5, 0);
		TooltipPlayer.AttackLifeFrame.SilenceState:SetNormalTexture(135975);
		--TooltipPlayer.AttackLifeFrame.SilenceState:SetFrameLevel(TooltipPlayer:GetFrameLevel() + 4);
		TooltipPlayer.AttackLifeFrame.SilenceState:Hide();
		TooltipPlayer.AttackLifeFrame.SilenceState:SetScript("OnLeave", WC_Lib.OnLeave);
		TooltipPlayer.AttackLifeFrame.SilenceState:SetScript("OnEnter", function(self) 
			GameTooltip:SetOwner(self, "ANCHOR_TOP");
			GameTooltip:AddLine("|cffc04bba"..core.L["Silence"].." ("..IsSilenceMobsFight[6]..")|r");
			GameTooltip:Show();
		end);
		
		
		-- POSITION MODE --
		mainFrame.positionsFrame = CreateFrame("Frame", nil, mainFrame);
		mainFrame.positionsFrame:SetSize(280,170);
		mainFrame.positionsFrame:SetPoint("BOTTOMLEFT", mainFrame, "BOTTOMLEFT", 20, 20);
		mainFrame.positionsFrame:SetFrameLevel(mainFrame:GetFrameLevel() + 20);
		
		mainFrame.positionsFrame.titlePositionMode = mainFrame.positionsFrame:CreateFontString(nil, "OVERLAY", nil, mainFrame.positionsFrame);
		mainFrame.positionsFrame.titlePositionMode:SetFontObject("GameFontHighlightLarge");
		mainFrame.positionsFrame.titlePositionMode:SetPoint("TOP");
		mainFrame.positionsFrame.titlePositionMode:SetText(core.L["Configuration Position"]);
		mainFrame.positionsFrame.descPositionMode = mainFrame.positionsFrame:CreateFontString(nil, "OVERLAY", nil, mainFrame.positionsFrame);
		mainFrame.positionsFrame.descPositionMode:SetFontObject("GameFontNormal");
		mainFrame.positionsFrame.descPositionMode:SetPoint("TOP", mainFrame.positionsFrame.titlePositionMode, "BOTTOM", 0, -10);
		mainFrame.positionsFrame.descPositionMode:SetSize(250, 50);
		mainFrame.positionsFrame.descPositionMode:SetText(core.L["Déplacer, à l'aide de votre souris, le model 3D sur la scène pour sauvegarder ses positions."]);
		
		mainFrame.positionsFrame.btnChangeBg = CreateFrame("Button", nil, mainFrame.positionsFrame, "UIPanelButtonTemplate");
		mainFrame.positionsFrame.btnChangeBg:SetSize(125, 30);
		mainFrame.positionsFrame.btnChangeBg:SetText(core.L["Background"]);
		mainFrame.positionsFrame.btnChangeBg:SetPoint("TOP", mainFrame.positionsFrame.descPositionMode, "BOTTOM", 0, 0);
		mainFrame.positionsFrame.btnChangeBg:SetScript("OnClick", function() ShowListBgPicture(true) end);
		
		mainFrame.positionsFrame.SavePosition = CreateFrame("Button", nil, mainFrame.positionsFrame, "UIPanelButtonTemplate");
		mainFrame.positionsFrame.SavePosition:SetSize(125, 30);
		mainFrame.positionsFrame.SavePosition:SetText(core.L["Sauvegarder"]);
		mainFrame.positionsFrame.SavePosition:SetPoint("BOTTOM", mainFrame.positionsFrame, "BOTTOM");
		mainFrame.positionsFrame.SavePosition:SetScript("OnClick", function(self)
			local sceneUnit = self:GetParent():GetParent().infoUnit.scene;
			sceneUnit[currentPositionForSaving].position[1],
			sceneUnit[currentPositionForSaving].position[2],
			sceneUnit[currentPositionForSaving].position[3] = mainFrame.ModelScene[currentPositionForSaving]:GetPosition();

			sceneUnit.UIScale = UIParent:GetScale();

			sceneUnit[currentPositionForSaving].position.rotation = mainFrame.ModelScene[currentPositionForSaving]:GetFacing();
			
			_G["WC_AdventureFightScene"].ModelScene[currentPositionForSaving]:Hide();
			_G["WC_AdventureFightScene"].ModelScene[currentPositionForSaving]:Show();

			UpdateVersionAdventure(self:GetParent():GetParent().infoUnit, 2);
		end);
		mainFrame.positionsFrame.titleCurrentPosition = mainFrame.positionsFrame:CreateFontString(nil, "OVERLAY", nil, mainFrame.positionsFrame);
		mainFrame.positionsFrame.titleCurrentPosition:SetFontObject("GameFontNormalLarge");
		mainFrame.positionsFrame.titleCurrentPosition:SetPoint("BOTTOM", mainFrame.positionsFrame.SavePosition, "TOP", 0, 10);
		
		mainFrame.positionsFrame.buttonL = CreateFrame("Button", nil, mainFrame.positionsFrame, BackdropTemplateMixin and "BackdropTemplate");
		mainFrame.positionsFrame.buttonL:SetSize(32, 32);
		mainFrame.positionsFrame.buttonL:SetPoint("RIGHT", mainFrame.positionsFrame.SavePosition, "LEFT", -5, 0);		
		mainFrame.positionsFrame.buttonL:SetNormalTexture("Interface/Buttons/UI-SpellbookIcon-PrevPage-Up");
		mainFrame.positionsFrame.buttonL:SetPushedTexture("Interface/Buttons/UI-SpellbookIcon-PrevPage-Down");
		mainFrame.positionsFrame.buttonL:SetHighlightTexture("Interface/Buttons/UI-Common-MouseHilight");
		mainFrame.positionsFrame.buttonL:SetScript("OnClick", function(self)
			local position = nil;
			if currentPositionForSaving == 1 then
				position = 6;
			else
				position = currentPositionForSaving - 1;
			end
			UpdateFramePosition(position);
		end);
		
		mainFrame.positionsFrame.buttonR = CreateFrame("Button", nil, mainFrame.positionsFrame, BackdropTemplateMixin and "BackdropTemplate");
		mainFrame.positionsFrame.buttonR:SetSize(32, 32);
		mainFrame.positionsFrame.buttonR:SetPoint("LEFT", mainFrame.positionsFrame.SavePosition, "RIGHT", 5, 0);		
		mainFrame.positionsFrame.buttonR:SetNormalTexture("Interface/Buttons/UI-SpellbookIcon-NextPage-Up");
		mainFrame.positionsFrame.buttonR:SetPushedTexture("Interface/Buttons/UI-SpellbookIcon-NextPage-Down");
		mainFrame.positionsFrame.buttonR:SetHighlightTexture("Interface/Buttons/UI-Common-MouseHilight");
		mainFrame.positionsFrame.buttonR:SetScript("OnClick", function(self)
			local position = nil;
			if currentPositionForSaving == 6 then
				position = 1;
			else
				position = currentPositionForSaving + 1;
			end
			UpdateFramePosition(position);
		end);
	end
	
	_G["WC_AdventureFightScene"].infoUnit = infoUnit;	
	ResetFightAdventures();
	if infoUnit then -- IS POSITION MODE
		_G["WC_AdventureFightScene"]:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/adventures/backgrounds/"..WCCreator_Lib.structures.adventures.Info_SettingFight.backgroundPosMode,
								 edgeFile = "Interface/Tooltips/UI-Tooltip-Border", 
								 tile = false, edgeSize = 12,
								 insets = { left = 3, right = 3, top = 3, bottom = 3 }});
		for i = 1, 6 do
			_G["WC_AdventureFightScene"].ModelScene[i]:SetFrameLevel(_G["WC_AdventureFightScene"]:GetFrameLevel() + 11);
			_G["WC_AdventureFightScene"].ModelScene[i]:SetScript("OnMouseDown", WC_Lib.ModelOnMouseDown);
			_G["WC_AdventureFightScene"].ModelScene[i]:SetScript("OnMouseUp", WC_Lib.ModelOnMouseUp);
			
			_G["WC_AdventureFightScene"].ModelScene[i]:SetDisplayInfo(infoUnit.displayId);
			_G["WC_AdventureFightScene"].TooltipScene[i]:SetScript("OnEnter", nil);
			_G["WC_AdventureFightScene"].TooltipScene[i].AttackLifeFrame.lifeText:SetText(infoUnit.pdv);
			_G["WC_AdventureFightScene"].TooltipScene[i].AttackLifeFrame.damageText:SetText(infoUnit.damage);
			SetPositionModel(i, infoUnit.scene[i].position, infoUnit.scene.UIScale);
		end
		_G["WC_AdventureFightScene"].FFbtn:SetText(core.L["Retour"]);
		_G["WC_AdventureFightScene"].positionsFrame:Show();
		
		UpdateFramePosition(1);
	else -- IS FIGHT MODE
		if infoFight then
			curr_infoFight = infoFight;
		else
			infoFight = curr_infoFight;
		end
		
		local background = "Interface/FrameGeneral/UI-Background-Marble";
		if infoFight.background ~= "" then
			background = "Interface/AddOns/WoWChallenger/images/adventures/backgrounds/"..infoFight.background;
		end
		_G["WC_AdventureFightScene"]:SetBackdrop({bgFile = background,
							 edgeFile = "Interface/Tooltips/UI-Tooltip-Border", 
							 tile = false, edgeSize = 12,
							 insets = { left = 3, right = 3, top = 3, bottom = 3 }});

		for i = 1, #infoFight.mobs do
			--_G["WC_AdventureFightScene"].ModelScene[i]:SetFrameLevel(_G["WC_AdventureFightScene"]:GetFrameLevel() + 5);
			_G["WC_AdventureFightScene"].ModelScene[i]:SetScript("OnMouseDown", nil)
			_G["WC_AdventureFightScene"].ModelScene[i]:SetScript("OnMouseUp", nil)
			if _G["WC_AdventureFightScene"].InteractScene[i] then -- checking because player dont have interact frame
				_G["WC_AdventureFightScene"].TooltipScene[i]:SetScript("OnEnter", OnEnterTooltipEnnemyAdventureFight);
				--_G["WC_AdventureFightScene"].InteractScene[i]:SetFrameLevel(_G["WC_AdventureFightScene"]:GetFrameLevel() + 7);
			end
		end
		
		for i = 1, #infoFight.mobs do
			local unit = WC_Lib.SearchThingInAdventureByID(infoFight.mobs[i], 2, currentAddon);
			if unit then
				SummonUnit(i, unit);
				if i == 6 then
					RefreshStatesPlayer();
				end
			end
		end
		
		RefreshFrameLevelModel();
		_G["WC_AdventureFightScene"].FFbtn:Enable();
		_G["WC_AdventureFightScene"].FFbtn:SetText(core.L["Abandonner"]);
		_G["WC_AdventureFightScene"].positionsFrame:Hide();
		NextTurn(true);
	end
	
	if _G["WCC_UnitEditFrames"] then
		_G["WCC_UnitEditFrames"]:Hide();
	end
	if (_G[addon.."_InfoModelUnitAdventure"]) then
		_G[addon.."_InfoModelUnitAdventure"]:Hide();
	end

	_G["WC_AdventureFightScene"]:Show();
end