--#===============================================================================================================================#
--This function takes care of saving our settings, or sets up to load a save file.
--#===============================================================================================================================#
local XSon = XSon
local FILENAME = "client/XSonic/XS-settings-v1-0.dat"

XSon.SaveLoad = function(p, dosave, doload, SILENT)
	if not (p and p.valid) 
	or not p.xsonictable
	or ((isdedicatedserver) and (p==server))
		return --
	end
	local xs = p.xsonictable
	if doload --We're loading!
		if splitscreen and p==players[1] --You don't get a save!
			xs.hasloaded = true
		end 
		if xs.hasloaded==true return end --
		if io
			local file = io.openlocal(FILENAME)
			if file!=nil
				local code = file:read("*a")
				if code ~= nil and (string.find(code, "XSLoad ")) and not (string.find(code, ";"))
	--				print("5:\x83"+"Attempt LOAD INPUT:\x80 "+tostring(code))
				--	if not (SILENT)
				--		CONS_Printf(p, "\x83"+"Attempted load for\x84 X Sonic \x86 - jointime("+p.jointime+")")
				--	end	
					COM_BufInsertText(p, " "+(tostring(code)))
				end		
				file:close()
			end
		end
		return true --
				
	elseif dosave and (p == consoleplayer) and io --We're saving!
		local s1 = {}
		s1[1] = (xs.HUDpref==true) and 1 or 0 --HUD preference. True means the X Sonic HUD, otherwise it's the vanilla HUD.
			--see below for s1[2]!
		s1[3] = (xs.voice==true) and 1 or 0 --Play X Sonic's voice?
		s1[4] = (xs.tutorials=="all") and 2 or (xs.tutorials=="mild") and 1 or 0 --Use tutorials?
		s1[5] = (xs.FourKidsRB) and 1 or 0 --4kids RingBurst or Original?
		s1[6] = (xs.coopPvP) and 1 or 0 --Coop PVP. (Super Tenkaichi, getting kicked, etc.)
		s1[7] = (xs.ACCE=="both") and 3 or (xs.ACCE=="noflashes") and 2 or (xs.ACCE=="noquakes") and 1 or 0 --ACCEssibility
		s1[8] = (xs.SP_FakeEmeralds!=nil) and xs.SP_FakeEmeralds or 0
		s1[9] = (xs.C3tutorial==0) and 1 or 0
		s1[10] = (xs.SuperTimeAttack) and 1 or 0
		
		--Condense this a bit awkwardly to save space.
		if xs.SPcolor
			s1[2] = (string.gsub(tostring(R_GetNameByColor(xs.SPcolor)), " ", "blurwhyPLZ")) 
			if not (type(s1[2]) == "string")
				s1[2] = p.skincolor --failsafe.
			end
		else
			s1[2] = p.skincolor --We can safely save & load colors as either numbers or strings.
		end
		if xs.SuperTimeAttack
			if xs.SuperTimeAttack == "Dark"
				s1[10] = 2
			elseif xs.SuperTimeAttack == "FullDark"
				s1[10] = 3
			elseif xs.SuperTimeAttack == "Super"
				s1[10] = 4
			end
		end
		
		local file,WRITE = io.openlocal(FILENAME, "w+"), "XSLoad "
		for i = 1,#s1
			WRITE = $+s1[i]+" "
		end
		file:write(WRITE) file:close()
		if SILENT != 7
			CONS_Printf(p, "\x8b"+"Updated saved settings for\x84"+" X Sonic")
		end
		xs.hasloaded = true return true --
	end
end

--Why do we need a command to load stuff? Because otherwise it's clientside and won't load in netgames. Which is dumb, yes, I know.
COM_AddCommand("XSLoad", function(p, a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
	if (gamestate ~= GS_LEVEL)
	or not (p.valid)
	or splitscreen==true and p==players[1]
	or ((isdedicatedserver) and (p==server))
		return --
	end	
	
	local xs = p.xsonictable
	if not (xs) or (xs.hasloaded)
		return --
	end
	
	--print("\x84"+"CC LOADING:\x80 "+a1+" "+a2+" "+" "+a3+" "+a4+" "+a5+" "+a6+a7+a8+a9+"\x82 "+a10)
	
	a1,a3,a4,a5 = tonumber($), tonumber($), tonumber($), tonumber($) --All of you except a2! Numbers, NOW!
	a6,a7,a8,a9,a10 = tonumber($), tonumber($), tonumber($), tonumber($),tonumber($)
	if a1 == 0
		xs.HUDpref = false
	end
	if a3 == 0
		xs.voice = false
	end
	xs.tutorials = (a4==0) and "none" or (a4==1) and "mild" or "all"
	if a5 == 1
		xs.FourKidsRB = true
	end
	if a6 == 0
		xs.coopPvP = nil
	end
	xs.ACCE = (a7==3) and "both" or (a7==2) and "noflashes" or (a7==1) and "noquakes" or nil
	if a8
		if (netgame != true) and spstage_start==1 --Only load these in the vanilla campaign, when singleplayer.
			local MAP = mapheaderinfo[1]
			if MAP and (MAP.lvlttl == "Greenflower")
				XS_FAKEEMERALDS = max(0, min(127, a8))
			end
		end
		xs.SP_FakeEmeralds = max(0, min(127, a8)) --Personal emerald progress, unrelated to what you actually have.
	end
	if a9 == 1
		xs.C3tutorial = 0
	end
	if a2 --Regardless of it being Single Player or not, at least load the color.
		local COLOR = a2
		local OLDCOLOR = COLOR
		
		if type(COLOR) == "string"
			COLOR = string.gsub(COLOR, "blurwhyPLZ", " ")  
			OLDCOLOR = COLOR
			COLOR = R_GetColorByName(COLOR) 
		end
		if type(COLOR) != "number" 
			COLOR = tonumber(COLOR)
		end
		if type(COLOR) == "number" 
			local MAXCOLORS = #skincolors
			if COLOR==0 or (COLOR > MAXCOLORS)
				CONS_Printf(p, "\x85"+"Failed to load"+"\x80 "+OLDCOLOR+"\x85 custom color!\x80 Using \x84"+"SONIKKU")
				COLOR = SKINCOLOR_SONIKKU
			end
		else
			COLOR = SKINCOLOR_SONIKKU
		end
		xs.SPcolor = COLOR
		if not ( (G_GametypeHasTeams()) and (p.ctfteam))
			if IsXSonic(p.mo, p)
				p.skincolor = COLOR
				if p.mo
					if not ( (p.powers[pw_shield]) and (p.powers[pw_shield] & SH_FIREFLOWER) )
						p.mo.color = COLOR	
					end
					XSon.RememberXColor(p,p.mo,xs)
				end
			end
		end
		if p.mo and p.mo.XS_PreDarkColor==nil
			p.mo.XS_PreDarkColor = xs.SPcolor
		end
	end
	if a10
		if a10==2
			xs.SuperTimeAttack = "Dark"
		elseif a10==3
			xs.SuperTimeAttack = "FullDark"
		elseif a10==4
			xs.SuperTimeAttack = "Super"	
		else
			xs.SuperTimeAttack = "AllEmeralds"
		end
		if ((marathonmode) or (modeattacking))
			XSon.SuperTimeAttack(p, p.mo, xs) --Function itself checks for X Sonic and p.mo.
		end
	end
	if p.mo and IsXSonic(p.mo, p) --Correct the HUD if you became X Sonic, btw.
		XSon.SwapHUD(p,p.mo,xs, "correct", true)
	end
	if (xs.hasloaded!=true)
		CONS_Printf(p, "\x8b"+"Loaded"+"\x84 X Sonic\x8b settings!")
		xs.hasloaded = true
	end return true --
end)