-- flying_strings.lua

require("util.glfont")
local mm = require("util.matrixmath")

flying_strings = {}
flying_strings.__index = flying_strings

local SquidLib = require("scene.tree3")

function flying_strings.new(...)
    local self = setmetatable({}, flying_strings)
    if self.init ~= nil and type(self.init) == "function" then
        self:init(...)
    end 
    return self
end

function flying_strings:init()
    self.vbos = {}
    self.vao = 0
    self.prog = 0
    self.dataDir = nil
    self.glfont = nil
    self.towardsCenter = 0
    self.textFlatten = 1
    self.strings = {}

    self.Squid = SquidLib.new()
    self.phase = 0 -- To fit with contained scene's keyframe name
    self.Squid.fogDensity = .35
end

function flying_strings:setDataDirectory(dir)
    self.dataDir = dir

    -- Load text file
    local filename = "names.txt"
    if self.dataDir then filename = self.dataDir .. "/" .. filename end
    local file = io.open(filename)
    if file then
        for line in file:lines() do
            table.insert(self.strings, line)
        end
    end

    self.strings_in_space = {}
    for _,v in pairs(self.strings) do
        local spr = 2
        local xspr = 2*2
        table.insert(self.strings_in_space, {
            -- String, location, phase
            v,
            {
                -xspr+2*xspr*math.random(),
                -spr+2*spr*math.random(),
                0,
            },
            math.random(),
        })
    end
end

function flying_strings:initGL()
    dir = "fonts"
    if self.dataDir then dir = self.dataDir .. "/" .. dir end
    self.glfont = GLFont.new('amiga_forever.fnt', 'amiga_forever_0.raw')
    self.glfont:setDataDirectory(dir)
    self.glfont:initGL()
    self.Squid:initGL()
end

function flying_strings:exitGL()
    self.glfont:exitGL()
    self.Squid:exitGL()
end

function flying_strings:renderEye(model, view, proj)
    local col = {0.5,0.5,0.5}

    self.Squid.phase = self.phase

    self.Squid:renderEye(model, view, proj)
    gl.glClear(GL.GL_DEPTH_BUFFER_BIT)

    for _,v in pairs(self.strings_in_space) do
        local m = {}
        for i=1,16 do m[i] = model[i] end
        local s = .004
        local tx = {}
        for i=1,3 do tx[i] = v[2][i] end
        local a = self.towardsCenter + v[3]
        a = a - math.floor(a)
        local center = {-2,-2,-10}
        for i=1,3 do
            tx[i] = a*center[i] + (1-a)*tx[i]
        end
        tx[3] = tx[3] * self.textFlatten
        mm.glh_translate(m, tx[1], tx[2], tx[3])
        mm.glh_scale(m, s, -s, s)
        mm.pre_multiply(m, view)
        self.glfont:render_string(m, proj, col, v[1])
    end
end

function flying_strings:render_for_one_eye(view, proj)
end

function flying_strings:timestep(absTime, dt)
    local t = .4 * absTime
    --self.towardsCenter = t - math.floor(t)
    self.Squid:timestep(absTime, dt)
end

return flying_strings
