-- This Source Code Form is subject to the terms of the bCDDL, v. 1.1.
-- If a copy of the bCDDL was not distributed with this
-- file, You can obtain one at http://beamng.com/bCDDL-1.1.txt

local M = {}

local lastObjectName = nil
local function getObjectName(tbl)
  return tbl.partOrigin or "main"
end

local function needGroupStatement(name)
  return lastObjectName ~= name
end

local function save()
  local objPath = v.vehicleDirectory .. '/export.obj'
  local f = io.open(objPath, "w")
  
  --failed?
  if not f then 
    print("Failed to save : cannot open " .. objPath)
    return
  end
  
  --export obj!
  --remap and export nodes
  local nodeIndexRemap = {}
  local currentNodeId = 1
  
  for _,node in pairs(v.data.nodes) do
    --remap
    nodeIndexRemap[node.cid] = currentNodeId
    currentNodeId = currentNodeId + 1
    
    --write position
    f:write(string.format("v %f %f %f\n", node.pos.x * -1, node.pos.z, node.pos.y))
  end
  
  --start with beams
  local objectName = "main"
  for _, beam in pairs(v.data.beams) do
    --object name new?
    local objName = getObjectName(beam)
    if needGroupStatement(objName) then
      lastObjectName = objName
      f:write(string.format("g %s\n",objName))
    end
    
    --create a line
    local vertIndexA = nodeIndexRemap[beam.id1]
    local vertIndexB = nodeIndexRemap[beam.id2]
    
    f:write(string.format("l %i %i\n", vertIndexA, vertIndexB))
  end
 
 --then do triangles, and that's really all we can export to obj
 for _, triangle in pairs(v.data.triangles) do
    --object name new?
    local objName = getObjectName(triangle)
    if needGroupStatement(objName) then
      lastObjectName = objName
      f:write(string.format("g %s\n",objName))
    end
    
    --create a tri
    local vertIndexA = nodeIndexRemap[triangle.id1]
    local vertIndexB = nodeIndexRemap[triangle.id2]
    local vertIndexC = nodeIndexRemap[triangle.id3]
    f:write(string.format("f %i %i %i\n", vertIndexA, vertIndexB, vertIndexC))
 end
 
 print(string.format("Saved OBJ file at %s", objPath))
  f:close()
end

M.export = save
return M