-- If existing log file found, load and append to it
local mergedMessage = LoadResourceFile(GetCurrentResourceName(), string.format("LOGS/log-%s.log", os.date("%m-%d-%Y"))) or ""

--
-- log.lua
--
-- Copyright (c) 2016 rxi
--
-- This library is free software; you can redistribute it and/or modify it
-- under the terms of the MIT license. See LICENSE for details.
--
-- https://github.com/rxi/log.lua

local modes = {
  { name = "info",  color = "^5", },
  { name = "warn",  color = "^3", },
  { name = "error", color = "^8", },
}

log.messages = { }

local levels = {}
for i, v in ipairs(modes) do
  levels[v.name] = i
end


local round = function(x, increment)
  increment = increment or 1
  x = x / increment
  return (x > 0 and math.floor(x + .5) or math.ceil(x - .5)) * increment
end


local _tostring = tostring

local tostring = function(...)
  local t = {}
  for i = 1, select('#', ...) do
    local x = select(i, ...)
    if type(x) == "number" then
      if x % 1 ~= 0 then
        x = round(x, 0.01)
      end
    elseif type(x) == "table" then
	  x = json.encode(x)
	end
    t[#t + 1] = _tostring(x)
  end
  return table.concat(t, " ")
end


for i, x in ipairs(modes) do
  local nameupper = x.name:upper()
  log[x.name] = function(...)
    local msg = tostring(...)
    --[[local info = debug.getinfo(2, "Sl")
	-- Remove resource name and file path, uneeded
	info.short_src = string.match(info.short_src, ".+/(.-)$")
    local lineinfo = info.short_src .. ":" .. info.currentline]]


    -- Output to console			
	if i >= levels[log.consoleLevel] then
	  local consoleMsg = string.format("%s[%-6s%s]%s %s %s",
						 log.usecolor and x.color or "",
						 nameupper,
						 os.date("%H:%M:%S"),
						 --	Highlight whole line for errors and warning
						 log.usecolor and x.name ~= "warn" and x.name ~= "error" and "^7" or "",
						 msg,
						 -- Reset coloring in case of warn/error or coloring
						 "^7")  
	  print(consoleMsg)
    end		

    -- Store the log message
	if i >= levels[log.fileLevel] then
	  local fileMsg = string.format("[%-6s%s] %s",
                      nameupper,
                      os.date("%H:%M:%S"),
                      msg)
      table.insert(log.messages, fileMsg)
	end
  end
end

-- Function to write stored messages to the outfile
log.writeToFile = function()
	local fileName = string.format("LOGS/log-%s.log", os.date("%m-%d-%Y"))
    for _, message in ipairs(log.messages) do
		mergedMessage = mergedMessage..message..'\n'
    end
    local result = SaveResourceFile(GetCurrentResourceName(), fileName, mergedMessage, -1)
	return result, fileName
end