--[[
	rocketdemoinlua.lua

	A bare-bones implementation of a demo in Luajit/OpenGL, reveicing keyframes
	from GNU rocket, playing a song, and simply changing the clear color.

	https://github.com/emoon/rocket/tree/master/sync
]]
local rk = require("rocket")
package.loadlib("socket/core.dll", "luaopen_socket_core")
local socket = require("socket.core")
local fpstimer = require( "util.fpstimer" )

local bass = require("bass")
local glfw = require( "GLFW" )
local openGL = require( "opengl" )
openGL.loader = glfw.glfw.GetProcAddress
openGL:import()

local g_ft = fpstimer.create()

local bpm = 150.0 -- beats per minute
local rpb = 8 -- rows per beat
local row_rate = (bpm / 60) * rpb
local row_time = 0.0
local current_row = 0
local last_sent_row = 0
local paused = 1
local stream = nil

function cb_pause(flag)
	if stream then
		if flag == 1 then
			bass.BASS_ChannelPause(stream)
		else
			bass.BASS_ChannelPlay(stream, false)
		end
	end
end

function cb_setrow(row)
	current_row = row
	last_sent_row = row
	row_time = row / row_rate

	local pos = bass.BASS_ChannelSeconds2Bytes(stream, row / row_rate)
	bass.BASS_ChannelSetPosition(stream, pos, bass.BASS_POS_BYTE)
end

function cb_isplaying()
	--return (paused == 0)
	return (bass.BASS_ChannelIsActive(stream) == bass.BASS_ACTIVE_PLAYING)
end

local cbs = {
	cb_pause,
	cb_setrow,
	cb_isplaying
}

function onkey(window,k,code,action,mods)
    if action == glfw.GLFW.PRESS or action == glfw.GLFW.REPEAT then
        if k == glfw.GLFW.KEY_ESCAPE then os.exit(0)
        end
    end
end

function display()
	local r = rk.get_value("clear.r", current_row) or 0
	local g = rk.get_value("clear.g", current_row) or 0
	local b = rk.get_value("clear.b", current_row) or 0
    gl.ClearColor(r,g,b,0)
    gl.Clear(GL.COLOR_BUFFER_BIT + GL.DEPTH_BUFFER_BIT)
end

function init_gl()
end

function timestep(obj, dt)
	if cb_isplaying() then
		row_time = row_time + dt
		current_row = math.floor(row_rate * row_time)
	else
		socket.sleep(0.001)
	end
end

function main()
	if arg[1] and arg[1] == "sync" then
		SYNC_PLAYER = 1
	end

	if SYNC_PLAYER then
		local success = rk.connect_demo()
		tracknames = {
			"clear.r",
			"clear.g",
			"clear.b",
		}
		for k,v in pairs(tracknames) do
			rk.create_track(v)
			rk.send_track_name(rk.obj, v)
		end
	else
		--print("Load tracks from file")
		local tracks_module = 'tracks'
		local status, module = pcall(require, tracks_module)
		if not status then
			print('Tracks file ['..tracks_module ..'.lua] not found.')
			print('Re-launch with argument sync to connect to editor.')
			print('')
			print('Press any key to exit...')
			io.read()
			os.exit(1)
		end
		rk.sync_tracks = module
	end

	
	glfw.glfw.Init()

	local windowTitle = "Lua Demo"
	window = glfw.glfw.CreateWindow(800,600,windowTitle,nil,nil)
	glfw.glfw.MakeContextCurrent(window)
	glfw.glfw.SetKeyCallback(window, onkey)
	glfw.glfw.SetWindowSizeCallback(window, resize)

	local init_ret = bass.BASS_Init(-1, 44100, 0, 0, nil)
	stream = bass.BASS_StreamCreateFile(false, "data/tunechop.ogg", 0, 0, bass.BASS_STREAM_PRESCAN)

	bass.BASS_Start()
	bass.BASS_ChannelPlay(stream, false)


	init_gl()
    g_lastFrameTime = os.clock()
	while glfw.glfw.WindowShouldClose(window) == 0 do
		if SYNC_PLAYER then
			local uret = rocket.sync_update(rocket.obj, current_row, cbs)
			if uret ~= 0 then
				--print("sync return: "..uret)
				--rk.connect_demo()
			end
		end

		glfw.glfw.PollEvents()
		g_ft:onFrame()
		display()

        timestep(rocket.obj, os.clock() - g_lastFrameTime)
        g_lastFrameTime = os.clock()
		glfw.glfw.SetWindowTitle(window, windowTitle.." "..math.floor(g_ft:getFPS()).." fps")
		glfw.glfw.SwapBuffers(window)
	end

	bass.BASS_StreamFree(stream)
	bass.BASS_Free()
end

main()
