--[[ camera4.lua

]]

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

camera4 = {}
camera4.__index = camera4

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

function camera4:init()
    self.clickpos = {0,0}
    self.clickrot = {0,0}
    self.holding = false
    self.objrot = {0,0}
    self.objtrans = {0,0,0}
    self.camera4pan = {0,0,0}
    self.camerarot = {0,0} -- x,y TODO: quat
    self.chassis = {0,0,2}
    self.keymove = {0,0,0}
    self.altdown = false
    self.ctrldown = false
    self.shiftdown = false
    self.keystates = {}

    self:reset()
end

function camera4:reset()
    self.objrot = {0,90}
    self.objtrans = {0,0,0}

    -- TODO: consolidate these 2
    self.chassis = {0,0,1}
    self.camera4pan = {0,0.5,3}

    self.camerarot = {0,15}
end

function camera4:timestep(absTime, dt)
    for i=1,3 do
        self.chassis[i] = self.chassis[i] + dt * self.keymove[i]
    end
end

function camera4:getModelMatrix()
    local m = {}
    mm.make_identity_matrix(m)
    mm.glh_translate(m,
        self.objtrans[1], 
        self.objtrans[2], 
        self.objtrans[3])
    mm.glh_rotate(m, -self.objrot[1], 0,1,0)
    mm.glh_rotate(m, -self.objrot[2], 1,0,0)
    return m
end

function camera4:getViewMatrix()
    local v = {}
    mm.make_identity_matrix(v)

    -- Lookaround camera
    mm.glh_translate(v, self.chassis[1], self.chassis[2], self.chassis[3])
    mm.glh_translate(v, self.camera4pan[1], self.camera4pan[2], self.camera4pan[3])

    mm.glh_rotate(v, -self.camerarot[1], 0,1,0)
    mm.glh_rotate(v, -self.camerarot[2], 1,0,0)

    return v
end

function camera4:handleCommand(args)
    if #args < 1 then return end

    if args[1] == 'reset' then
        self:reset()
    end
end

-- Return a list of strings(lines) describing commands and state
function camera4:commandHelp()
    local posstr = 'Pos: '
        ..tostring(self.camera4pan[1])..','
        ..tostring(self.camera4pan[2])..','
        ..tostring(self.camera4pan[3])

    local offstr = 'Off: '
        ..tostring(self.chassis[1])..','
        ..tostring(self.chassis[2])..','
        ..tostring(self.chassis[3])

    local rotstr = 'Rot: '
        ..tostring(self.camerarot[1])..','
        ..tostring(self.camerarot[2])

    return {
        'camera4 help',
        'Commands: reset',
        posstr,
        offstr,
        rotstr,
    }
end

return camera4
