---Global Var's---

town_array = {"town1","town2","town3"};
spells_hard = {1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 39, 236, 237};
spells_heroic = {7, 8, 15, 17, 19, 40, 42, 43};

visited=nil	--был ли реалаг у оракула
reinforce_day=nil --день прихода подмоги
timer=nil --день прихода Шадии
support=nil --имя героя пришедшего на подмогу
reinf = 0
startweek = 0
first = 0;
Graal_Found = 0;

messenger_limit = 4;
messenger = "";

---Message Boxes---
not_realag="/Maps/Scenario/C4M2/text/not_raelag.txt"
oracul_visited="/Maps/Scenario/C4M2/text/visited.txt"
---------------------
SetRegionBlocked("a1", 1, PLAYER_2);
SetRegionBlocked("a2", 1, PLAYER_2);
SetRegionBlocked("a3", 1, PLAYER_2);
SetRegionBlocked("a4", 1, PLAYER_2);
SetRegionBlocked("b1", 1, PLAYER_2);
SetRegionBlocked("c1", 1, PLAYER_2);
SetRegionBlocked("c2", 1, PLAYER_2);
SetRegionBlocked("c3", 1, PLAYER_2);
---Dialog Scenes---
C4M2D1="/DialogScenes/C4/M2/D1/DialogScene.xdb#xpointer(/DialogScene)"
C4M2R1="/DialogScenes/C4/M2/R1/DialogScene.xdb#xpointer(/DialogScene)"
C4M2R2="/DialogScenes/C4/M2/R2/DialogScene.xdb#xpointer(/DialogScene)"
C4M2R3="/DialogScenes/C4/M2/R3/DialogScene.xdb#xpointer(/DialogScene)"
C4M2R4="/DialogScenes/C4/M2/R4/DialogScene.xdb#xpointer(/DialogScene)"
C4M2R5="/DialogScenes/C4/M2/R5/DialogScene.xdb#xpointer(/DialogScene)"
C4M2R6="/DialogScenes/C4/M2/R6/DialogScene.xdb#xpointer(/DialogScene)"
C4M2R7="/DialogScenes/C4/M2/R7/DialogScene.xdb#xpointer(/DialogScene)"
C4M2D2="/DialogScenes/C4/M2/D2/DialogScene.xdb#xpointer(/DialogScene)"
C4M2D3="/DialogScenes/C4/M2/D3/DialogScene.xdb#xpointer(/DialogScene)" ---------Новая !!!
--difficulty
if GetDifficulty() == DIFFICULTY_EASY then
	diff = 0;
	AddObjectCreatures("Raelag", 72, 20);
	print("isi");
end;

if GetDifficulty() == DIFFICULTY_NORMAL then
	diff = 1;
	print("normal");
end;

if GetDifficulty() == DIFFICULTY_HARD then
	diff = 2;
	messenger_limit = 5;
	DenyAIHeroesFlee(2, 1);
	DenyAIHeroesFlee(3, 1);
	print("hard!");
end;

if GetDifficulty() == DIFFICULTY_HEROIC then
	diff = 3;
	messenger_limit = 6;
	for i=0,5 do
		SetPlayerResource(2,i,50);
	end;
	SetPlayerResource(2,6,80000);
	DenyAIHeroesFlee(2, 1);
	DenyAIHeroesFlee(3, 1);
	print("heroic!");
end;

---functions---
function warlok_up(player)
	local heroes = GetPlayerHeroes(player);
	if diff > 1 then
		startThread(add_army, "post1", 0.5 * (diff-1));
		startThread(add_army, "post2", 0.5 * (diff-1));
	end;
	if heroes ~= {} then
		for i, hero in heroes do
			ChangeHeroStat(hero, 0, 2000 + diff * 5000 + random(5) * 2000);
			if diff > 1 then
				startThread(add_army, hero, 0.25 * (diff-1));
				startThread(teach_spell, hero, spells_hard, diff + 1);
				if diff > 2 then
					startThread(teach_spell, hero, spells_heroic, 3);
					for j=1,4 do
						if random(2) == 0 then
							ChangeHeroStat(hero, j, 1);
						end;
					end;
				end;
			end;
		end;
	end;
end;

function teach_spell(hero, array, num)
	if IsHeroAlive(hero) then
		local k = 0;
		local l = length(array);
		local m = 2 * (l - mod(l,num))/num
		for i, spell in array do
			if k < num then
				if random(m) == 0 and KnowHeroSpell(hero, spell) == nil then
					TeachHeroSpell(hero, spell);
					k = k + 1;
				end;
			end;
		end;
	end;
end;

function add_army(mon, ind)
	if IsObjectExists(mon) then
		for i = 1, 90 do
			if GetObjectCreatures(mon, i) > 0 then
				AddObjectCreatures(mon, i, ind * GetObjectCreatures(mon, i));
			end;
		end;
	end;
end;

function MoveHeroPatch(hero, x, y, z)
	print("move hero "..hero.." to point "..x.." "..y);
	local player = GetObjectOwner(hero);
	local x1,y1,z1 = GetObjectPosition(hero);
	while IsHeroAlive(hero) do
		sleep(2);
		while GetCurrentPlayer() ~= player do
			sleep(2);
		end;
		while GetCurrentPlayer() == player do
			sleep(2);
			if IsHeroAlive(hero) then
				x1,y1,z1 = GetObjectPosition(hero);
				if z1 == z then
					MoveHeroRealTime(hero, x, y, z);
					else MoveHero(hero, 73, 100, 0);
				end;
				sleep(2);
			end;
		end;
		ChangeHeroStat(hero, 7, -10000);
	end;
end;

function find_weak(player)
	local heroes = GetPlayerHeroes(player);
	local weaker = "";
	if length(heroes) > 2 then
		for i, hero in heroes do
			if i > 0 and IsObjectExists(hero) then
				if GetHeroPower(hero) < GetHeroPower(heroes[i-1]) then
					weaker = hero;
				end;
				else weaker = hero;
			end;
		end;
	end;
	return weaker;
end;

function GetHeroPower(hero)
	local power = 0;
	if IsObjectExists(hero) then
		for i=1,90 do
			if GetObjectCreatures(hero, i) > 0 then
				power = power + GetObjectCreatures(hero, i);
			end;
		end;
	end;
	return power;
end;

function PObjective3()
	while GetTownBuildingLevel( "Angkar", TOWN_BUILDING_GRAIL ) ~= 1 do
--		print ("working");
		sleep( 5 );
		if ( Graal_Found == 1 ) and ( IsAnyHeroPlayerHasArtifact( PLAYER_1, ARTIFACT_GRAAL ) == nil ) then
--			SetObjectiveState( "prim2", OBJECTIVE_FAILED );
			sleep( 5 );
			if GetTownBuildingLevel( "Angkar", TOWN_BUILDING_GRAIL ) ~= 1 then
				Loose();
			end;
			return
		end;
	end;
end;

function Graal()
	print ("start");
	while IsAnyHeroPlayerHasArtifact( PLAYER_1, ARTIFACT_GRAAL ) == nil do
		sleep(2);
	end;
	startThread( PObjective3 );
	print ("end");
	Graal_Found = 1;
	if visited==nil then
		visited=true
		SetObjectiveState('prim2',OBJECTIVE_ACTIVE)
		sleep(1)
		SetObjectiveState('prim1',OBJECTIVE_COMPLETED)
	end;
end;

function IsAnyHeroPlayerHasArtifact( playerID, artifID )
	local heroes = {};
	local m = 0;
	local h = 0;
	heroes = GetPlayerHeroes( playerID );
	for m, h in heroes do
		if HasArtefact( h, artifID ) then
			return true;
	    end;
	end;
	return nil;
end;

function oracul(name) --фэйковая функциональность оракула, комплит первой и старт второй обжектив, вызывается триггером
	if name=='Raelag' then
		if visited==nil then
			visited=true
			StartDialogScene(C4M2D2) --Сцена посещения оракула
			SetObjectiveState('prim2',OBJECTIVE_ACTIVE)
			OpenCircleFog( 28, 139, 1, 5, PLAYER_1 ); ---фог вокруг выхода
			sleep(1)
			SetObjectiveState('prim1',OBJECTIVE_COMPLETED)
			GiveExp( "Raelag", 500 ); ---addexp!!!
			return
		else
			MessageBox(oracul_visited) -- фраза при повторном посещении
		end
	else
		MessageBox(not_realag) -- к оракулу зашел не Раелаг, оракул говорит:"ты кто такой? иди в бобруйск!"
	end
end

function post_capturing() --вызывается триггером, после первой активации вызвающий триггер снимаетс
	StartDialogScene(C4M2R1) --Сцена посещения гарнизона
	SetObjectiveState('prim3',OBJECTIVE_ACTIVE)
	sleep(1)
	Trigger(OBJECT_CAPTURE_TRIGGER, "post1", nil)
	Trigger(OBJECT_CAPTURE_TRIGGER, "post2", nil)
end

function levelup() --вызывается из консоли если карта проходится отдельно от кампании (чтобе привести Раелага к нужному уровню)
	ChangeHeroStat('Raelag', STAT_EXPERIENCE,4600)
end

function town_triggering() --вызывается в начале миссии, развешивает триггеры на все города АИ
	for i,town in town_array do
		Trigger(OBJECT_CAPTURE_TRIGGER, town, "town_capture")
	end
end

function town_capture() --вызывается триггером, после первой активации вызвающий триггер снимаетс
	StartDialogScene(C4M2R3) --Сцена на захват перврго города.
	sleep(1)
	SetObjectiveState('sec1', OBJECTIVE_ACTIVE)
	startThread( Mess_go_1 ) ----------------///////DB
	Trigger(PLAYER_REMOVE_HERO_TRIGGER , PLAYER_2, 'kill_messenger');
	timer=GetDate(ABSOLUTE_DAY)+1;
	Trigger(NEW_DAY_TRIGGER,'delay');
	Trigger(REGION_ENTER_WITHOUT_STOP_TRIGGER, 'escape1', 'remove_messanger');
	Trigger(REGION_ENTER_WITHOUT_STOP_TRIGGER, 'escape2', 'remove_messanger');
	for i,town in town_array do
		Trigger(OBJECT_CAPTURE_TRIGGER, town, nil)
	end
	startweek = GetDate(WEEK)
end
-----------------------------------------////////////DB
function Mess_go_1()
	while messenger_limit > 0 do
		sleep(20);
		if messenger == "" then
			messenger = find_weak(2);
			if messenger ~= ""  then
				if IsObjectExists(messenger) then
					print("find messenger "..messenger);
					EnableHeroAI(messenger, nil);
					if random(2) == 0 then
						startThread(MoveHeroPatch, messenger, 59, 173, 0);
						else startThread(MoveHeroPatch, messenger, 2, 131, 0);
					end;
					while IsHeroAlive(messenger) do
						sleep(10);
					end;
				end;
			end;
		end;
		if reinf > 0 then
			break;
		end;
		sleep(20);
	end;
end;

function kill_messenger(hero)
	if hero == messenger then
		messenger = "";
		messenger_limit = messenger_limit - 1;
		print("messenger was killed!");
	end;
end;

function remove_messanger(heroname)
	if GetObjectOwner(heroname)==PLAYER_2 and heroname == messenger then
		RemoveObject(heroname);
		Trigger(REGION_ENTER_WITHOUT_STOP_TRIGGER, 'escape1', nil);
		Trigger(REGION_ENTER_WITHOUT_STOP_TRIGGER, 'escape2', nil);
		Trigger(PLAYER_REMOVE_HERO_TRIGGER , 2, nil);
		reinf = 1;
	end
end

function hero_update()
	k = GetDate(WEEK) - startweek;
	print( "k = "..k );
	ChangeHeroStat('Inagost', STAT_EXPERIENCE, 8000 + k * 5000 );
	AddObjectCreatures('Inagost', CREATURE_ASSASSIN, 150 + random(7) + k*7 + 50 * diff);
	AddObjectCreatures('Inagost', CREATURE_RAVAGER, 40 + random(4) + k*4 + 10 * diff);
	AddObjectCreatures('Inagost', CREATURE_MATRIARCH, 16 + random(2) + k*2 + 4 * diff);
	AddObjectCreatures('Inagost', CREATURE_BLACK_DRAGON, 5 + k + diff );
	startThread(warlok_up, 3);
	if diff == 3 then
		SetHeroLootable('Inagost', nil);
		GiveArtefact('Inagost', 1);
		GiveArtefact('Inagost', 8);
		GiveArtefact('Inagost', 9);
		GiveArtefact('Inagost', 20);
		GiveArtefact('Inagost', 22);
		GiveArtefact('Inagost', 39);
		GiveArtefact('Inagost', 38);
		GiveArtefact('Inagost', 36);
		GiveArtefact('Inagost', 25);
		TeachHeroSpell('Inagost', 9);
		TeachHeroSpell('Inagost', 18);
		TeachHeroSpell('Inagost', 235);
	end;
end;

function Reinforcement_Adgot()
	if ( random( 2 ) == 1 ) then
		DeployReserveHero('Inagost', 59, 173, 0)
	else
		DeployReserveHero('Inagost', 2, 131, 0)
	end
	sleep(1)
	SetObjectiveState('sec2', OBJECTIVE_ACTIVE) ------Появляется герой противника!!!!
	hero_update()
	Trigger(PLAYER_REMOVE_HERO_TRIGGER, PLAYER_3, 'adgot_hero_death');
	--Trigger(NEW_DAY_TRIGGER,nil) --после срабатывания триггер снимается чтобы не мешалс
end;

function delay() --вызывается триггером
	if GetDate(ABSOLUTE_DAY)==timer then
		StartDialogScene(C4M2D3) --Сцена появления Шадии
		sleep(1)
		SetObjectiveState('prim5', OBJECTIVE_ACTIVE)
		DeployReserveHero('Kelodin', 14, 156, 1)
	end
	if reinf == 1 then
		StartDialogScene(C4M2R4) --Сцена если пропустили гонцов
		sleep(1)
		SetObjectiveState('sec1', OBJECTIVE_FAILED)
		startThread( Reinforcement_Adgot )
		reinf = 2;
	end
end

function script_crap()
	DeployReserveHero('Inagost', 59, 173, 0)
	sleep(1)
	hero_update()
end

function adgot_hero_death(heroname)
	if heroname=='Inagost' then
		StartDialogScene(C4M2R5) --Сцена когда разгромим пришедшего героя
		SetObjectiveState('sec2',OBJECTIVE_COMPLETED)
		GiveExp( "Raelag", 3000 ); ---addexp!!!
		Trigger(NEW_DAY_TRIGGER, nil);
	end
end

function objective2()
	if GetObjectiveState('prim2')==OBJECTIVE_COMPLETED then
		ChangeHeroStat("Raelag", STAT_LUCK, 3);  -------Oblico_Morale!
		StartDialogScene(C4M2R6) --Сцена после постройки грааля
		sleep(2)
		startThread(WinConditions);
	end
end

function objective3()
	if GetObjectiveState('prim3')==OBJECTIVE_COMPLETED then
		ChangeHeroStat("Raelag", STAT_LUCK, 3);  -------Oblico_Morale!
		if first == 0 then
			startThread( Test1 );
			StartDialogScene(C4M2R2); --Сцена на захват всех городов клана
			first = 1;
		end;
		sleep(2)
		startThread(objective3_1); ---проверка гонцов нв комплит
		startThread(WinConditions);
	end
end
----------------------------///
function objective3_1()
	if ( GetObjectiveState('prim3')==OBJECTIVE_COMPLETED ) and ( GetObjectiveState('sec1') == OBJECTIVE_ACTIVE )then
		sleep(2)
		SetObjectiveState('sec1', OBJECTIVE_COMPLETED) ---комплит гонцов
	end
end
----------------------------///
function WinConditions()
	if ( GetObjectiveState('prim3') == OBJECTIVE_COMPLETED ) and ( GetObjectiveState('prim2') == OBJECTIVE_COMPLETED )then
		sleep(2);
		if HasArtefact("Raelag", 13) then
			SetGameVar("C4M2_Raelag_AFH", 1);
			else SetGameVar("C4M2_Raelag_AFH", 0);
		end;
		if HasArtefact("Kelodin", 13) then
			SetGameVar("C4M2_Kelodin_AFH", 1);
			else SetGameVar("C4M2_Kelodin_AFH", 0);
		end;
--		SetObjectiveState('prim5',OBJECTIVE_COMPLETED)
		SetObjectiveState('prim6',OBJECTIVE_COMPLETED)
		GiveExp( "Raelag", 5000 ); ---addexp!!!
		sleep(10)
		print("Victoria................................!!!")
		Win();
	end
end;

function player_hero( name )
	if ( name == "Raelag" ) then -- raelag was eliminated
		SetObjectiveState( 'prim6', OBJECTIVE_FAILED )
		sleep(1)
		print("Raelag_kaput................................!!!")
		Loose()
	elseif ( GetObjectiveState( 'prim5') == OBJECTIVE_ACTIVE ) and ( name == "Kelodin" ) then -- shadya was eliminated
		SetObjectiveState( 'prim5', OBJECTIVE_FAILED )
		sleep(1)
		print("Shadia_kaput................................!!!")
		Loose();
	end;
end

------------------------------------------!!!!Last
Trigger( REGION_ENTER_AND_STOP_TRIGGER, "escape1","Start_ai" );

function Start_ai( heroname )
	if IsPlayerHeroesInRegion(2, "escape1") == true and GetObjectOwner(heroname)==PLAYER_2 then
		sleep( );
		EnableHeroAI( heroname, true )
	end;
end;

---------------------------------------------------!!

SetPlayerHeroesCountNotForHire(1, 4 )

------------------------I find clovers!
--Trigger( REGION_ENTER_AND_STOP_TRIGGER, "t1","One", nil );
--Trigger( REGION_ENTER_AND_STOP_TRIGGER, "t2","Two", nil );

--function One()
--Trigger( REGION_ENTER_AND_STOP_TRIGGER, "t1", nil );
--SetObjectPosition("Raelag", 68, 122, 0);
--CreateArtifact("Clover", ARTIFACT_FOUR_LEAF_CLOVER, 67, 122, 0);
--end;

--function Two()
--Trigger( REGION_ENTER_AND_STOP_TRIGGER, "t2", nil );
--SetObjectPosition("Raelag", 30, 149, 0);
--end;
-------------------------------
function Test1()
	local enemy = {};
	enemy = GetPlayerHeroes(PLAYER_2);
	for i, hero in enemy do
		RemoveObject(hero);
	end;
end;

------------------------Script Start---

town_triggering()
StartDialogScene(C4M2D1) --Сцена стартовая
OpenCircleFog( 46, 137, 1, 5, PLAYER_1 );
SetObjectEnabled('oracul', nil);
Trigger(OBJECT_CAPTURE_TRIGGER, "post1", "post_capturing")
Trigger(OBJECT_CAPTURE_TRIGGER, "post2", "post_capturing")
Trigger(OBJECT_TOUCH_TRIGGER, "oracul", "oracul")
SetTrigger(OBJECTIVE_STATE_CHANGE_TRIGGER , 'prim2', 'objective2')
SetTrigger(OBJECTIVE_STATE_CHANGE_TRIGGER , 'prim3', 'objective3')
Trigger(PLAYER_REMOVE_HERO_TRIGGER , PLAYER_1, 'player_hero')
sleep (20);
startThread( Graal );
startThread(warlok_up, 2);
print("all started!")