-- Game State ----------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------
-- CreateConsole()
-- global values
life_is_good = 9876543210

-- Init values
username = GetCurrentUser(); 					-- Get current player name. String
savepath = GetSavePath() .. username .. ".sav"; -- Get save path. String
text_sheet = "re"; 								-- Text sheet const
sheet = "gr"; 									-- Tool sheet const
gamedata = {};									-- Table of logical game data
gamedata.id_index = 50000;						-- Starting value of objects id index
gamedata.curr_level_name = "lvl1com1";					-- Starting level
gamedata.curr_level = 31;
gamedata.curr_sublevel = 0;

obj = {};										-- Unique objects id dictionary
flags = {};										-- Dictionary of logical game flags

-- WriteToConsole("Core")

-- Functions for internal use -----------------------------------------------------------------------

-- function DeleteCurrentSave()
	-- username = GetCurrentUser();
	-- savepath = GetSavePath() .. username .. ".sav";
	-- os.remove( savepath );
-- return; end;

-- table.save/table.load ----------------------------------------------------------------------------
do
-- declare local variables
--// exportstring( string )
--// returns a "Lua" portable version of the string
local function exportstring( s )
	s = string.format( "%q",s )
	-- to replace
	s = string.gsub( s,"\\\n","\\n" )
	s = string.gsub( s,"\r","\\r" )
	s = string.gsub( s,string.char(26),"\"..string.char(26)..\"" )
	return s
end

filename = GetSavePath() .. "log";

function WriteLog(str)
	file = io.open( filename, "a");
	file:write(str .. "\n");
	file:close();
return; end;
	
--// The Save Function
function table.save(  tbl,filename )
	local charS,charE = "   ","\n"
	local file,err
	-- create a pseudo file that writes to a string and return the string
	if not filename then
		file =  { write = function( self,newstr ) self.str = self.str..newstr end, str = "" }
		charS,charE = "",""
	-- write table to tmpfile
	elseif filename == true or filename == 1 then
		charS,charE,file = "","",io.tmpfile()
	-- write table to file
	-- use io.open here rather than io.output, since in windows when clicking on a file opened with io.output will create an error
	else
		file,err = io.open( filename, "w" )
		if err then return _,err end
	end
	-- initiate variables for save procedure
	local tables,lookup = { tbl },{ [tbl] = 1 }
	file:write( "return {"..charE )
	for idx,t in ipairs( tables ) do
		if filename and filename ~= true and filename ~= 1 then
			file:write( "-- Table: {"..idx.."}"..charE )
		end
		file:write( "{"..charE )
		local thandled = {}
		for i,v in ipairs( t ) do
			thandled[i] = true
			-- escape functions and userdata
			if type( v ) ~= "userdata" then
				-- only handle value
				if type( v ) == "table" then
					if not lookup[v] then
						table.insert( tables, v )
						lookup[v] = #tables
					end
					file:write( charS.."{"..lookup[v].."},"..charE )
				elseif type( v ) == "function" then
					file:write( charS.."loadstring("..exportstring(string.dump( v )).."),"..charE )
				else
					local value =  ( type( v ) == "string" and exportstring( v ) ) or tostring( v )
					file:write(  charS..value..","..charE )
				end
			end
		end
		for i,v in pairs( t ) do
			-- escape functions and userdata
			if (not thandled[i]) and type( v ) ~= "userdata" then
				-- handle index
				if type( i ) == "table" then
					if not lookup[i] then
						table.insert( tables,i )
						lookup[i] = #tables
					end
					file:write( charS.."[{"..lookup[i].."}]=" )
				else
					local index = ( type( i ) == "string" and "["..exportstring( i ).."]" ) or string.format( "[%d]",i )
					file:write( charS..index.."=" )
				end
				-- handle value
				if type( v ) == "table" then
					if not lookup[v] then
						table.insert( tables,v )
						lookup[v] = #tables
					end
					file:write( "{"..lookup[v].."},"..charE )
				elseif type( v ) == "function" then
					file:write( "loadstring("..exportstring(string.dump( v )).."),"..charE )
				else
					local value =  ( type( v ) == "string" and exportstring( v ) ) or tostring( v )
					file:write( value..","..charE )
				end
			end
		end
		file:write( "},"..charE )
	end
	file:write( "}" )
	-- Return Values
	-- return stringtable from string
	if not filename then
		-- set marker for stringtable
		return file.str.."--|"
	-- return stringttable from file
	elseif filename == true or filename == 1 then
		file:seek ( "set" )
		-- no need to close file, it gets closed and removed automatically
		-- set marker for stringtable
		return file:read( "*a" ).."--|"
	-- close file and return 1
	else
		file:close()
		return 1
	end
end

--// The Load Function
function table.load( sfile )
	-- catch marker for stringtable
	if string.sub( sfile,-3,-1 ) == "--|" then
		tables,err = loadstring( sfile )
	else
		tables,err = loadfile( sfile )
	end
	if err then return _,err
	end
	tables = tables()
	for idx = 1,#tables do
		local tolinkv,tolinki = {},{}
		for i,v in pairs( tables[idx] ) do
			if type( v ) == "table" and tables[v[1]] then
				table.insert( tolinkv,{ i,tables[v[1]] } )
			end
			if type( i ) == "table" and tables[i[1]] then
				table.insert( tolinki,{ i,tables[i[1]] } )
			end
		end
		-- link values, first due to possible changes of indices
		for _,v in ipairs( tolinkv ) do
			tables[idx][v[1]] = v[2]
		end
		-- link indices
		for _,v in ipairs( tolinki ) do
			tables[idx][v[2]],tables[idx][v[1]] =  tables[idx][v[1]],nil
		end
	end
	return tables[1]
end
end; -- close do
-- End table.save/table.load ------------------------------------------------------------------------

-- function DeleteCurrentSave()
	-- os.remove( savepath );
-- return; end;

-- Auto unique id -----------------------------------------------------------------------------------
function NewId(name) -- name must be string
	if type(name) ~= "string" then 
		messagebox("Wrong type(" .. type(name) ..") of name param");
	return; end;
	
	if obj[name] == nil then
		obj[name] = {};
	end;
	
	if not obj[name].id then
		gamedata.id_index = gamedata.id_index + 1;
		obj[name].id = gamedata.id_index;
	--else
		--messagebox("There was a try to duplicate id of " .. tostring(name) .. " object");
	end;
	return obj[name].id;
end;
-- End of Auto id -----------------------------------------------------------------------------------
-- End Functions for internal use -------------------------------------------------------------------

function SaveGame1()
	gamedata.flags = flags;
	gamedata.obj = obj;
	gamedata.nextlvl=nextlevel;
	table.save( gamedata, savepath );
end;

function LoadGame()
	if io.open( savepath, "r" ) then
		gamedata = table.load( savepath );
		flags = gamedata.flags;
		obj = gamedata.obj;
		nextlevel=gamedata.nextlvl
	end;

end;

function NextLevel( nextlevel, next_sublevel )
	-- TODO: implement switching of levels here
  -- c("\n 1")
	setnextlavel( nextlevel );
	 -- c("\n 2")
		c("\n Next Level  =  "..nextlevel.."\n" )
	loadlavel();

		c( "\nLevel has been loaded\n" )
	gamedata.curr_level = nextlevel;
	 c("\n 333333")
	--gamedata.current_sublevel = next_sublevel;	
	-- messagebox("NextLevel: gamedata.current_level = " .. gamedata.current_level);
	-- End TODO
end;

function NewObj(name, resname, x, y, notice, ... ) -- No "" param!
--addactivobjecttogame(name, resname, x, y, "", notice, xstring, ystring, xtexture, ytexture, width, height, simmetry, groupname);
	
	addactivobjecttogame( NewId(name), resname, x, y, "", notice, unpack(arg) );
	if obj[name].is_stored then
		set_visible_object( obj[name].id, false );
	 end;
	if notice ~= "" then -- Adding text labels to text sheet
		AddElement( text_sheet, obj[name].id );
		-- setcolor( obj[name].id,1,1,1,1,1 );
		if obj[name].is_collapsed then
			setcolor( obj[name].id,0.255,0.427,0.459,1,1 );
		end;
	end;
	
	if obj[name].is_collapsed == true then
		set_visible_object( obj[name].id, false );
	end;
	
	if obj[name].is_stored then
		 AddElement( sheet, obj[name].id );	
			MoveObjectToTree(obj[name].id);		 
	return; end;
end;
function NewObj1(name, resname, x, y, notice, ... ) -- No "" param!
--addactivobjecttogame(name, resname, x, y, "", notice, xstring, ystring, xtexture, ytexture, width, height, simmetry, groupname);

	 addactivobjecttogame( NewId(name), resname, x, y, "", notice, unpack(arg) );
	 obj[name].is_collapsed=true
	 -- Set_Cursor(obj[name].id,4)
	-- if obj[name].is_stored then
		-- set_visible_object( obj[name].id, false );		
	 -- end;
	if notice ~= "" then -- Adding text labels to text sheet
		
		-- if obj[name].is_collapsed then
			-- setcolor( obj[name].id,0.255,0.427,0.459,1,1 );
		-- end;
	end;
	
	-- if obj[name].is_collapsed == true then
		-- set_visible_object( obj[name].id, false );
	-- end;
		if obj[name].is_stored then
	
		AddElement( sheet, obj[name].id );		
		MoveObjectToTree(obj[name].id);
	return; end;
end;

function CollapseObj(obj_id, coll_speed, coll_time)
playeffect("011")
	for i,v in pairs(obj) do
		if obj[i].id == obj_id then
			if not coll_speed then
				coll_speed = 20;
			end;
			if not coll_time then
				coll_time = 0.5;
			end;
			collaps_obj(obj_id, 0, 0, coll_speed, coll_time);
			-- setcolor(obj_id,0.7,0.7,0.7,1,1);
			obj[i].is_collapsed = true;
		return; end;
	end;
end;

function StoreObj1(obj_id)
playeffect("016")
	for i,v in pairs(obj) do
		if obj[i].id == obj_id then
			AddElement(sheet,obj_id);
			MoveObjectToTree(obj_id);
			obj[i].is_stored = true;
			switched=true;
			AlternateTimer("SwitchSheet1",700)
		return; end;
	end;
end;

function StoreObj(obj_id)
playeffect("016")
	for i,v in pairs(obj) do
		if obj[i].id == obj_id then
			AddElement(sheet,obj[i.."1"].id);
			MoveObjectToTree(obj[i.."1"].id);			
			obj[i.."1"].is_stored = true;
			switched=true;
			AlternateTimer("SwitchSheet",700)
			takeobjecttohand=false
		return; end;
	end;
end;






function UnStoreObj(obj_id)
	for i,v in pairs(obj) do
		if obj[i].id == obj_id then
			DeleteElement(sheet,obj_id);
			obj[i].is_stored = false;
		return; end;
	end;
end;


function SwitchSheet()

if takeobjecttohand then return;end;
SwitchToSheet("re");
end
function SwitchSheet1()
c("eeeeSwitch!!!")
if takeobjecttohand then return;end;
SwitchToSheet("gr");
-- AlternateTimer("plashechkiGameInput1",1500)
end

function StopColorColl()
colorcollapse=false
end
-----------------------------------------------------------------------------------------------------
-- End Game State -----------------------------------------------------------------------------------

function AddLevel( level_name, level, sublevel )
	-- dofile("./data/" .. level .. "/init.lua");

	add_free_leaf( level_name );
	dofile("./data/".. level .."/init.lua");
	-- dofile("./data/0/50/level.lua");
end;

function SetLevel( level_name, level, sublevel )
	add_free_leaf( level_name );
	dofile("./data/" .. level .. "/init.lua");
	
	 set_activ_free_leaf( level_name );
	
    dofile("./data/" .. level .. "/" .. sublevel .. "/level.lua");
	gamedata.curr_level_name = level_name;
	gamedata.curr_level = level;
	gamedata.curr_sublevel = sublevel;
end;

function DropLevel( parent_name, level_name )
	delete_tree_leaf( parent_name, level_name );
end;

function AddSatellite( parent_name, level, sublevel )
	add_free_leaf( parent_name );
	dofile("./data/".. level .."/init.lua");	
end;

function SetSatellite( parent_name, level, sublevel )
	dofile("./data/" .. level .. "/" .. sublevel .. "/res.lua");
	set_satelite_leaf( parent_name );
	dofile("./data/" .. level .. "/" .. sublevel .. "/level.lua");
end;

function DropSatellite( parent_name )
	clear_satelite_leaf( parent_name );
end;

--[[
add_tree_leaf() — добавление листа-уровня в дерево игры
1 Имя родительского узла
2 Номер уровня.
3 Номер подуровня.

setcurrentleaf() — установка текущего уровня
Имя листа-уровня.
1.
Номер уровня.
2.
Номер подуровня.
3.

set_activ_leaf() — установка активного листа-уровня
Имя листа-уровня.
1.

set_satelite_leaf() — установка листа спутника для комиксов и мини-игр
Имя локации, родительской для создаваемого спутника.
1.

clear_satelite_leaf() — удаление листа спутника
Имя родительской локации.
1.

delete_tree_leaf() — удаление уровня-листа
Имя родительского узла
1.
Имя узла.
2.
]]

local count =0;
local i=500000;
local coord = {};
local j=1;
local line=0;
local n=1;
local startX=0;
local startY=0;

flags.firstlevel=false
	

	
	
function PolyCoord(dest)
	
		if count ==0 then
		x,y = GetCursorPos()
		coord[j] =x; 		j=j+1;
		coord[j]=y;		    j=j+1;
		--count = count +1;		
		count =1;
		startX=x;
		startY=y;
		return;end;
		
		if count ==1 then			
		x1,y1=GetCursorPos()	
		if n==6 then n=1; end
		i=i+1;
		-- messagebox("tochka"..n)
		 AddLine(i,"tochka"..n,x,y,x1,y1,5);			
		speciale_action(4,i);		
		
		
		x=x1; y=y1;		
		coord[j]=x1;		j=j+1;
		coord[j]=y1;		j=j+1;
		line=line+1;	
		
		if x1 > startX -10 and x1 < startX+10 and y1 >startY-10 and y1<startY+10 then		
		io.output(io.open("data\\"..dest.."\\polygons.lua","a"))	
		io.write("CreatePolygon( "..(i-4)..", "..line.." { ");
		for i,v in pairs(coord) do				
		if i==table.maxn (coord) or i==(table.maxn (coord)-1) or i==(table.maxn (coord)-2) then	
		if i==(table.maxn (coord)-2) then
		io.write(coord[i]);
		end
		else
		io.write(coord[i]);
		io.write(", "); 
		end	
		end		
		
		io.write(" } ".." )".."\n");
		io.close();
		count=0;coord = {};	line=0;	j=1; 
		
		n=n+1; 		
		
		
		end;
		
		end;
		
		
end


-- sounds={{id=6,t=1},{id=5,t=2},{id=9,t=3},{id=3,t=4},{id=10,t=5},{id=11,t=6},{id=27,t=3},{id=1,t=4},{id=9,t=3},{id=5,t=2},{id=5,t=3},{id=6,t=7},{id=7,t=7},{id=8,t=5}}
repeats={}

timedelay=0
musiccount=1;
blackscore=0
function check(repeats)

if blackscore==40 then
	playeffect(r)					

return;end

blackscore=blackscore+1
for i=1,table.maxn(repeats) do		
			if (r==repeats[i]) then
					num= GetRandom(1,table.maxn(sounds))						
					r=sounds[num].id	
					timedelay=sounds[num].t						
					check(repeats)			
					
					
			end				
	end
end

function playmus()	
num= GetRandom(1,table.maxn(sounds))
	r=sounds[num].id	
	timedelay=sounds[num].t
	
	check(repeats)	
	repeats[musiccount]=r;	
	WriteToConsole("mus file = "..r.."\n")
	playfile(r,false,true)
	
	musiccount=musiccount+1;
	if musiccount==table.maxn(sounds)/2 then			
		repeats={}
		musiccount=1;			
	end	
	
	StartTimer(5644343,timedelay,"nextsound")
end
function nextsound()
playmus()
end

