--[[
  The Eye Helpers Library
  Script: The_Eye_Helpers
  Author: Divinity
  Version: 1.0
  Description: library for the eye.
]]

import(Module_Building);
import(Module_Commands);
import(Module_Control);
import(Module_DataTypes);
import(Module_Defines);
import(Module_Draw);
import(Module_Features);
import(Module_Game);
import(Module_Globals);
import(Module_Helpers);
import(Module_ImGui);
import(Module_Level);
import(Module_Map);
import(Module_MapWho);
import(Module_Math);
import(Module_Network);
import(Module_Objects);
import(Module_Person);
import(Module_Players);
import(Module_PopScript);
import(Module_Sound);
import(Module_Shapes);
import(Module_Spells);
import(Module_String);
import(Module_System);
import(Module_Table);

_gsi = gsi()
_gnsi = gnsi()
gs = gsi()
sti = spells_type_info()
pti = people_type_info()
tmi = thing_move_info()
--_gnsi.GameParams.Flags2 = _gnsi.GameParams.Flags2 | GPF2_GAME_NO_WIN
_gnsi.GameParams.Flags3 = _gnsi.GameParams.Flags3 | GPF3_NO_GAME_OVER_PROCESS
enable_feature(F_WILD_NO_RESPAWN)
--disable ally change!!!
_NO_SPELL_MODEL = M_SPELL_BURN --M_SPELL_NONE this can cause hyper fast shamans upon respawning i think
SAFE_NEUTRAL = TRIBE_NEUTRAL

include("mg_enums.lua")
include("mg_assets.lua")
include("mg_hub.lua")
include("mg_maps.lua")
include("mg_map_info.lua")
include("mg_library.lua")

include("_mg_color_battle.lua")
include("_mg_boat_wars_I.lua")
include("_mg_naval_warfare.lua")

remove_reincarnation_sites()
-- sti[2].OneOffMaximum = 1
-- sti[2].WorldCoordRange = 9000
-- _pti[7].ManaValue = 72
--PlayerSpellLimits[M_SPELL_BLAST].MaxCharges = 3

---------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------

mg_effects_list = {}
mg_obj_list = {}
mg_power_ups_list = {}
max_powerups_at_once = -1
powerups_pointer = nil
l_mouse_pressing = false
framer = 1
default_selected_map = 1
font_heights = {}
hub_log = {}
log_fading_timer = MAX_LOG_FADING_TIMER
log_glass_timer = MAX_LOG_GLASS_TIMER
highest_score_decimals = 1
mg_turn = 0

---------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------


player = {
			hovering_button = false,
			hovering_subbutton = false,
			mouse_in_game_id = false,
			dragging_card = false,
			dragging_card_from = false,
			card_size_cache = {},
			name_editing = false,
			name_editing_string = "",
			map_rules_line = 1,
			rules_full_lines = 8,
			end_line = 8,
			card_border = 1780,
			shaman_frame = 0,
			can_only_use_arrows = false,
			draw_hub = true,
			tooltip = false,
			scores_small_font = false,
			zoom_on_respawn = false,
			follow_forge = false,
			lock_moving = 0,
			lock_moving_id = false,
}

game = {
			loaded_mini_games = {},
			state = GAME_STATE_INITIALIZE, --GAME_STATE_FORGING,--GAME_STATE_INITIALIZE,
			unforging = false,
			master = TRIBE_BLUE,
			games_played = 0,
			--button_pressed_framer = 0,
			previous_map = nil,
			selected_map = default_selected_map,
			map_duration = nil,
			map_max_rounds = nil,
			map_target_score = nil,
			map_target_score_type = MAP_TYPE_SCORE_TRIBAL,
			map_objectives_tbl = {},
			past_game_stats = {}, --map id, teams & pts (depend on scoring type per mini-game), duration until end, 
			--stats_page = 1,
			sounds_muted = false,
			
			processing = false,
			mg_state = MG_STATE_COUNTDOWN,
			countdown = 0,
			
			map_players = 0,
			map_curr_duration = 0,
			map_curr_round = 0,
			map_curr_round_timer = -1,
			map_curr_teams_scoring = {},
			map_respawn_timer = 1,
			shield_respawn = false,
			
			over = false
}

players = {
			[0] = 	{ tribe=0, mode=TRIBE_IS_EMPTY_SLOT, points=0, played_games=0, full_name="", short_name="", curr_team=nil, color=4,		g_color=2, ready=false, master=true, spectator=false, sounds_cdr=0, 	sprite=6879,	spec_spr=7922,	ready_spr=7120,	card=1762 },
					{ tribe=1, mode=TRIBE_IS_EMPTY_SLOT, points=0, played_games=0, full_name="", short_name="", curr_team=nil, color=12,	g_color=-2, ready=false, master=false, spectator=false, sounds_cdr=0, 	sprite=6899,	spec_spr=7927,	ready_spr=7190,	card=1763 },
					{ tribe=2, mode=TRIBE_IS_EMPTY_SLOT, points=0, played_games=0, full_name="", short_name="", curr_team=nil, color=5,		g_color=3, ready=false, master=false, spectator=false, sounds_cdr=0, 	sprite=6919,	spec_spr=7932,	ready_spr=7260,	card=1732 },
					{ tribe=3, mode=TRIBE_IS_EMPTY_SLOT, points=0, played_games=0, full_name="", short_name="", curr_team=nil, color=3,		g_color=1, ready=false, master=false, spectator=true, sounds_cdr=0, 	sprite=6939,	spec_spr=7937,	ready_spr=7330,	card=1764 },
					{ tribe=4, mode=TRIBE_IS_EMPTY_SLOT, points=0, played_games=0, full_name="", short_name="", curr_team=nil, color=7,		g_color=10, ready=true, master=false, spectator=false, sounds_cdr=0, 	sprite=6879,	spec_spr=7922,	ready_spr=7120,	card=1765 },
					{ tribe=5, mode=TRIBE_IS_EMPTY_SLOT, points=0, played_games=0, full_name="", short_name="", curr_team=nil, color=6,		g_color=11, ready=true, master=false, spectator=false, sounds_cdr=0, 	sprite=6899,	spec_spr=7927,	ready_spr=7190,	card=1766 },
					{ tribe=6, mode=TRIBE_IS_EMPTY_SLOT, points=0, played_games=0, full_name="", short_name="", curr_team=nil, color=1,		g_color=12, ready=false, master=false, spectator=true, sounds_cdr=0, 	sprite=6919,	spec_spr=7932,	ready_spr=7260,	card=1740 },
					{ tribe=7, mode=TRIBE_IS_EMPTY_SLOT, points=0, played_games=0, full_name="", short_name="", curr_team=nil, color=14,	g_color=-1, ready=false, master=false, spectator=false, sounds_cdr=0, 	sprite=6939,	spec_spr=7937,	ready_spr=7330,	card=1767 }
}

gui_teams = {
				{ id = 1, default_name = "Solo Players", 	 								players = {}, locked = false, },
				{ id = 2, default_name = "Team A", 			curr_name = "Team A", 			players = {}, locked = false, played_games = 0, points = 0 },
				{ id = 3, default_name = "Team B", 			curr_name = "Team B", 			players = {}, locked = false, played_games = 0, points = 0 },
				{ id = 4, default_name = "Team C", 			curr_name = "Team C", 			players = {}, locked = false, played_games = 0, points = 0 },
				{ id = 5, default_name = "Team D", 			curr_name = "Team D", 			players = {}, locked = false, played_games = 0, points = 0 }
}

-- teams = {--id, name, players{}, score, total_score, final_position, color // { PLAYER=player, PTS=0, REINC=reinc }
				-- { id = 1, name = "Solo Players", 	players = {}, score = 0, 	total_score = 0, final_position = nil, captain_color = nil, },
				-- { id = 2, name = "Team 1", 			players = {}, score = 0, 	total_score = 0, final_position = nil, captain_color = nil, },
				-- { id = 3, name = "Team 2", 			players = {}, score = 0, 	total_score = 0, final_position = nil, captain_color = nil, },
				-- { id = 4, name = "Team 3", 			players = {}, score = 0, 	total_score = 0, final_position = nil, captain_color = nil, },
				-- { id = 5, name = "Team 4", 			players = {}, score = 0, 	total_score = 0, final_position = nil, captain_color = nil, }
-- } 
_participants = {}
_tribes_to_participants_ptrs = {[0]=nil,nil,nil,nil,nil,nil,nil,nil}
_tribes_to_teams_ptrs = {[0]=nil,nil,nil,nil,nil,nil,nil,nil}

past_teams = {} --id, name, players{}, points, played_games

---------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------

_state = game.state
_mg_state = game.mg_state
_map = game.selected_map
_map_duration = game.map_curr_duration
_map_scores = game.map_curr_teams_scoring
_map_info = map_list[_map]
_map_goals = _map_info.default_type_settings
_hovering = player.hovering_button
_subbutton = player.hovering_subbutton
_card = player.dragging_card
_card_from = player.dragging_card_from
_team_ffa = gui_teams[1].players
_team_1 = gui_teams[2].players
_team_2 = gui_teams[3].players
_team_3 = gui_teams[4].players
_team_4 = gui_teams[5].players
-- _participants = {}
-- _participants_pointers = {}
-- _participants_score_pointers = {}

---------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------
--local t = create_thing(T_PERSON, M_PERSON_BRAVE, TRIBE_BLUE, marker_to_coord3d(0), false,false)
--LOG(get_player_name(1, false))
set_player_name(1, "[Asffs44fdfsdvfht888", false) --LOG(get_player_name(1, false))
--local ttt = create_thing(T_SCENERY, M_SCENERY_HEAD, SAFE_NEUTRAL, marker_to_coord3d(0), false,false)


function OnTurn()
	local turn = gs.Counts.ProcessThings
	local everySecond1, everySecond2, everySecond4, everySecond8 = everySeconds(1), everySeconds(2), everySeconds(4), everySeconds(8)

	process_deforging(turn, everySecond1)
	OnTurn_action_function[_state](turn, everySecond1, everySecond2, everySecond4, everySecond8)
	
	if everySecond2 then

		-- tmi[TMI_PERSON_MEDICINE_MAN].BaseSpeed = math.random(8,127)
		-- sti[M_SPELL_TELEPORT].CursorSpriteNum = math.random(1, 4)
		
		-- sti[M_SPELL_BLAST].OneOffMaximum = math.random(1, 4)
		-- sti[M_SPELL_BLAST].Active = math.random(0, 1)
		--_gsi.ThisLevelInfo.PlayerThings[1].LimitsSpell[M_SPELL_BLAST].MaxCharges = 3
		--getPlayer(TRIBE_BLUE).LimitsSpell.MaxCharges[M_SPELL_BLAST] = math.random(1,5)
		--LOG(sti[M_SPELL_BLAST].OneOffMaximum)
		--getPlayer(TRIBE_BLUE).LimitsSpell.WorldCoordRange[M_SPELL_BLAST] = math.random(512,12000)
		
		try_to_terminate_game()
		--sti[2].OneOffMaximum = rndb(1,4)
		--sti[2].WorldCoordRange = rndb(3000,12000)
		--set_spell_charges(0, 2, rndb(1,4))
	end
end

function OnFrame()
	local w,h,guiW = ScreenWidth(), ScreenHeight(), GFGetGuiWidth()
	local mouseX, mouseY = get_mouse_x(), get_mouse_y()
	local four_framer = framer % 4 == 0
	--local four_framer, half_secondF, secondF = framer % 3 == 0, framer % 30 == 0, framer % 60 == 0
	
	OnFrame_action_function[_state](w, h, guiW, mouseX, mouseY, four_framer --[[half_secondF, secondF]])
	increase_framer()
	shaman_framer()
	--unpause_if_paused()
	frame_debug()
end

function OnMouseButton(key_num, is_down, x, y)
	local left = (key_num == LB_KEY_MOUSE0)
	
	if not is_down then
		OnMouseUp(left, x, y)
	else
		OnMouseDown(left, x, y)
	end
	
	gui_button_press(is_down, left)
end

function OnMouseUp(left, x, y)
	if left then
		l_mouse_pressing = false
	end
end

function OnMouseDown(left, x, y)
	if left then
		l_mouse_pressing = true
	end
end

function OnKeyDown(key) --LOG(key)
	-- if player.can_only_use_arrows then --LOG("locked")
		-- if key == 13 or key == 20 or key == 161 or (key >= 37 and key <= 40) then --LOG("allowed")
		
		-- else
			-- LOG("OK")
			-- return 1
		-- end
	-- end
end

function OnKeyUp(key)

	-- if player.can_only_use_arrows then
		-- if key == 13 or key == 20 or key == 161 or (key >= 37 and key <= 40) then
			-- return
		-- end
	-- end



	if key == 49 then --1
		end_game()
		--ttt.Model = 1
		--delete_thing_type(ttt)
		--ttt.State = 12
		--ttt.State = 12
		
		--0white, 1green, 2blue, 3yellow, ORA/BROWN, WHI/CYA, 6black, black, black, 9orange, cyan, pink, black

		--local sparkle = create_thing(T_EFFECT, M_EFFECT_SMALL_SPARKLE, SAFE_NEUTRAL, coord_to_c3d(24,24), false, false)
		--sparkle.DrawInfo.Alpha = -1
		--queue_fixed_sound_event(SND_EVENT_SWORD, 0)
		--make_land_on_square(24, 24, 24)
		--local t = create_thing(T_SCENERY, 3, 0, coord_to_c3d(24,24), false,false) t.AngleXZ = 1024
		
		-- local x, z = 96, 26
		-- local m = MapPosXZ.new()
		-- m.XZ.X = x
		-- m.XZ.Z = z
		
		-- SearchMapCells(SQUARE, 0, 0, 0, m.Pos, function(me)
			-- LOG(me.Alt)
		-- return true end)
		
		-- set_square_map_params(m.Pos, 6, TRUE)
		
		--local t = create_thing(T_PERSON, 2, 0, coord_to_c3d(x, z), false,false)

		
		
		--_t = create_thing(T_PERSON, M_PERSON_BRAVE, 0, marker_to_coord3d(28), false, false)
		--_t.DrawInfo.OnPersFrame:add(test_func)
		
		--getShaman(0).DrawInfo.OnPersFrame:add(shaman_bubbles)
	--elseif key == 50 then
		--getShaman(0).DrawInfo.OnPersFrame:remove(1)
	elseif key == 50 then
		--delete_thing_type(ttt)
	end
end

function OnCreateThing(t)
	local owner, type, model = t.Owner, t.Type, t.Model

	if OnCreateThing_action_function[_state] ~= nil then
		OnCreateThing_action_function[_state](t, owner, type, model)
	end
end

function OnSoundEvent(t_thing, event, flags)
	--doesnt seem to work properly, calls sounds whilte turn 0 (before setting funcs and variables), so can't do much with it
	--this is the only way (making funcs to spells, checking sounds first, and then map...)
	--ret = loadstring("ON_SND_VOLCANO" .. "_boat_wars_I((t_thing, event, flags))")() even loadstring doesnt work?
	--LOG(string.format("%s, %i, %i", tostring(t_thing), event, flags))
	
	local ret = FALSE
	
	if event == SND_EVENT_SHAM_VOLCANO or event == SND_EVENT_ESHAM_VOLCANO then
		if _map == MAP_BOAT_RACE_I then
			ret = TRUE
		end
	end
	
	return ret
end

function OnPlayerDeath(pn)
	disconnect_player(pn)
end

function OnPacket(playerNum, packet_type, data)
	--LOG("packet from " .. playerNum .. ", of type " .. packet_type .. ", with data " .. data)
	--receive_apm_packet(playerNum, data)
end

---------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------

