-- simpleclear.lua

local glfw = require( "GLFW" )
local openGL = require( "opengl" )
package.loadlib("socket/core.dll", "luaopen_socket_core")
local socket = require("socket.core")
local fpstimer = require( "util.fpstimer" )

openGL.loader = glfw.glfw.GetProcAddress
openGL:import()

local g_ft = fpstimer.create()

local params = {}

-- GNU Rocket #define SYNC_DEFAULT_PORT 1338
local obj = socket.tcp()
c = obj:bind("127.0.0.1", 1338)
obj:listen(32)
obj:settimeout(0)

function open_connection()
    -- If other instances are running, this will fail
    local client = obj:accept()
    if client == nil then
        return nil
    end
    client:settimeout(0)
    return client
end

-- Return of nil means connection is still alive
-- Non-nil means connection dropped.
function update_params(client, params)
    if client == nil then
        return 0
    end
    local s, status, r = client:receive("*l") -- get a line of text

    -- Parse incoming param values
    m = s or r
    if m then
        n = tonumber(m)
        if n then
            params['blue'] = n
        end
    end
    if status == nil then
        return nil
    end
    if status == "timeout" then
        return nil
    end
    return status
end

function main()
    glfw.glfw.Init()

    window = glfw.glfw.CreateWindow(800,600,"Luajit",nil,nil)
    glfw.glfw.MakeContextCurrent(window)

    local client = open_connection()

    params['red'] = 0
    params['blue'] = 0
    f = 0
    while glfw.glfw.WindowShouldClose(window) == 0 do
        glfw.glfw.PollEvents()
        g_ft:onFrame()
        glfw.glfw.SetWindowTitle(window, math.floor(g_ft:getFPS()).." fps")

        r = update_params(client, params)
        if r ~= nil then
            client = open_connection()
        end

        f = f + 1
        gl.ClearColor(params['red'], 0.5, params['blue'], 0.0)
        gl.Clear(GL.COLOR_BUFFER_BIT + GL.DEPTH_BUFFER_BIT)

        glfw.glfw.SwapBuffers(window)
    end
end

main()
