-- copy all globals into locals, some locals are prefixed with a G to reduce name clashes
local coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,Gload,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require=coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require

local pack=require("wetgenes.pack")
local wwin=require("wetgenes.win")
local wstr=require("wetgenes.string")
local tardis=require("wetgenes.tardis")	-- matrix/vector math


--module
local M={ modname=(...) } ; package.loaded[M.modname]=M

M.bake=function(state,game)
	local game=game or {}
	game.state=state
	
	local gl=state.gl
	local cake=state.cake
	local sheets=cake.sheets
	local opts=state.opts
	local canvas=cake.canvas
	local font=canvas.font
	local flat=canvas.flat

	game.layout=cake.layouts.create{}

	cake.game=game
	state.game=game

	local profiles=state.rebake("wetgenes.gamecake.spew.profiles")

	local beep=state.rebake("bulb.beep")

	
--	local input=state.rebake("bulb.input")
	local gui=state.rebake("bulb.gui")

	game.modname=M.modname
	
-- a substate
--	game.subs=require("wetgenes.gamecake.state").bake({
--		master=state,
--	})
	
	game.page="menu"
	game.wait=60
	
	
	
game.loads=function()

	state.cake.fonts.loads({1,"Vera","ostrich-black"}) -- load 1st builtin font, a basic 8x8 font
	
	sheets.loads_and_chops{

		{"button_move",1,1,0.5,0.5},
		{"button_select",1,1,0.5,0.5},
		{"button_back",1,1,0.5,0.5},
		{"button_continue",1,1,0.5,0.5},

		{"l1",1,1,0.5,0.5},
		{"r1",1,1,0.5,0.5},

		{"shopwheel",1,1,0.5,0.5},
		{"menuwheel",1,1,0.5,0.5},


		{"patterns/pattern5",1,1,0.5,0.5},
		{"scoreback",1,1,0.5,0.5},

		{"game",1,1,0.5,0.5},
		{"well",1,1,0.5,0.5},

		{"bulbs",128/1024,128/1024,64/1024,64/1024},
		
		{"scoreboard",1,1,0,0},
		{"scorebanner",1,1,0,0},
		
		{"popballs",1,1,0.5,0.5},
		{"poplevels",1,1,0.5,0.5},
		
		{"butt_popback",1,1,0.5,0.5},
		{"butt_popleft",1,1,0.5,0.5},
		{"butt_popright",1,1,0.5,0.5},
		{"butt_level",1,1,0.5,0.5},
		{"butt_level0",1,1,0.5,0.5},
		{"butt_level1",1,1,0.5,0.5},
		{"butt_level2",1,1,0.5,0.5},
		{"butt_level3",1,1,0.5,0.5},
		
		{"score00",1,1,0.5,0.5},
		{"score01",1,1,0.5,0.5},
		{"score02",1,1,0.5,0.5},
--		{"score03",1,1,0.5,0.5},
		{"score05",1,1,0.5,0.5},
		{"score06",1,1,0.5,0.5},
--		{"score07",1,1,0.5,0.5},
		{"score08",1,1,0.5,0.5},
		{"score09",1,1,0.5,0.5},
	}
	
end
		
game.setup=function()
	local cake=state.cake

	if oven.opts.smell=="gamestick" and oven.cake.images.exists("preloader") then
		oven.rebake("wetgenes.gamecake.spew.preloader").config{
			screen_hx=512,
			screen_hy=1024,
			screen_argb=0x00000000,
			text_dx= 300-1024,
			text_dy= 380-512,
			text_hx=-300+680,
			text_hy=-380+570,
			text_argb=0xff008800,
			text_rz=-2,
			img="preloader",
			img_hx=2048,
			img_hy=1024,
		}
	else
		oven.rebake("wetgenes.gamecake.spew.preloader").config_as("kittyscreen")
	end
			
			
	game.loads()
	
	game.last=nil
	game.now=nil
	game.next=nil
	
	game.unit=40 		-- play area is multiples of this wide/high
	game.bulb_size=64	-- the bulbs have an extra border all around them so are slightly bigger
	
	game.frame=0

-- preload all states
	state.rebake("bulb.pages").loads()
	state.rebake("bulb.game_play").loads()
	state.rebake("bulb.game_menu").loads()
	state.rebake("bulb.beep").loads()
	state.rebake("bulb.game_win").loads()
--gui setup
	gui.setup()
	
	game.next=state.rebake("bulb.game_intro")
	for i=1,#state.opts do
		if state.opts[i]=="play" then
			game.next=state.rebake("bulb.game_play")
			break
		elseif state.opts[i]=="menu" then
			game.next=state.rebake("bulb.game_menu")
			break
		elseif state.opts[i]=="intro" then
			game.next=state.rebake("bulb.game_intro")
			break
		elseif state.opts[i]=="edit" then
			game.next=state.rebake("bulb.game_edit")
			break
		end
	end
	
	game.change()
end

function game.change()

-- handle state changes

	if game.next then
	
		if game.now and game.now.clean then
			game.now.clean()
		end
		
		game.last=game.now
		game.now=game.next
		game.next=nil
		
		if game.now and game.now.setup then
			game.now.setup()
		end
		
	end
	
end		

game.clean=function()

	if game.now and game.now.clean then
		game.now.clean()
	end

end

game.msg=function(m)
--	print(wstr.dump(m))

	if m.xraw and m.yraw then	-- we need to fix raw x,y numbers
		m.x,m.y=game.layout.xyscale(m.xraw,m.yraw)	-- local coords, 0,0 is center of screen
		m.x=m.x+(320/2)
		m.y=m.y+(480/2)
	end

	if state.opts.smell=="gamestick" and m.class=="joykey" then
		if m.keyname=="button_x" or m.keyname=="button_y" then -- the gamestick bods really do not like keys to, uhm, do things.
			return
		end
	end

--[[
	if m.class=="key" then
		input.update_key(m.action,m.keyname,m.ascii)
	elseif m.class=="mouse" then
		input.update_mouse(m.action,m.x,m.y,m.keycode)
	end
]]

	if game.now and game.now.msg then
		game.now.msg(m)
	end
	
end

-- simple delayed profiler of one frame
local count=0
local count_prof=-100 -- set negative to disable
local function count_start()
	count=count+1
	if count==count_prof then
		print("profiler start")
		require("profiler").start("cache/frame"..count_prof..".log")
	end
end
local function count_stop()
	if count==count_prof then
		print("profiler stop")
		require("profiler").stop()
	end
end

game.update=function()

	game.change()

	
	game.frame=game.frame+1
	if game.now and game.now.update then
		game.now.update()
		beep.update()
	end


end

game.draw_crap=function(a,b,c,d)
	if state.opts.smell=="gamestick" then
		gl.Color(1,1,1)
		if a then cake.sheets.get("button_move"):draw(1, 	 	-60,     440, 0,480/8,640/8) end
		if b then cake.sheets.get("button_select"):draw(1,  	 320+60, 440, 0,480/8,640/8) end
		if c then cake.sheets.get("button_back"):draw(1, 		 320+120,440, 0,480/8,640/8) end
		if d then cake.sheets.get("button_continue"):draw(1,  	 320+220, 440, 0,480/8,640/8) end
--		if d then cake.sheets.get("button_continue"):draw(1,  	 -100, 220, 0,480/8,640/8) end
	end
end

game.draw=function()

count_start()
	
	game.layout.viewport() -- did our window change?
	game.layout.project23d(opts.width,opts.height,1/4,opts.height*4)

	canvas.gl_default() -- reset gl state

	gl.ClearColor(pack.argb4_pmf4(0xf000))
	gl.Clear(gl.COLOR_BUFFER_BIT)--+gl.DEPTH_BUFFER_BIT)

	gl.MatrixMode(gl.PROJECTION)
	gl.LoadMatrix( game.layout.pmtx )

	gl.MatrixMode(gl.MODELVIEW)
	gl.LoadIdentity()
	gl.Translate(-opts.width/2,-opts.height/2,-opts.height*2) -- top left corner is origin

	gl.PushMatrix()
	
	font.set(cake.fonts.get("ostrich-black")) -- default font
	font.set_size(32,0) -- 32 pixels high

	if game.now and game.now.draw then
		game.now.draw()
	end
	
	gl.PopMatrix()

count_stop()
	
end
		
	return game
end

