local onlinePlay

local onlineLogs = {}


local logFile

local function writeTimesToFile()
    logFile:write("- Local time: ".. os.date("%x").. ", ".. os.date("%X").. "\n")
    logFile:write("- UTC: ".. os.date("!%x").. ", ".. os.date("!%X"))
end

local function addZeroes(number,length)
    return string.format("%.".. length.. "d",number)
end


local function getFilename()
    local date = os.date("*t")

    local name = "logs/"

    name = name.. date.year.. "-".. addZeroes(date.month,2).. "-".. addZeroes(date.day,2).. "_"
    name = name.. addZeroes(date.hour,2).. "_"..addZeroes(date.min,2).. "_"..addZeroes(date.sec,2).. ".txt"

    return name
end


function onlineLogs.open(rawFilename)
    local filename = rawFilename or getFilename()

    logFile = io.open(Misc.levelPath().. filename,"a") or io.open(Misc.episodePath().. filename,"a")

    if logFile == nil then
        return nil
    end

    if rawFilename == nil then
        logFile:write("Log start:\n")
        writeTimesToFile()
        logFile:write("\n\n===============\n\n")
    end

    return filename
end

function onlineLogs.close()
    if logFile == nil then
        return
    end

    logFile:write("\n===============\n\n")
    logFile:write("Log end:\n")
    writeTimesToFile()

    logFile:close()
    logFile = nil
end

function onlineLogs.add(text)
    if logFile == nil then
        return
    end

    logFile:write(text.. "\n")
end


function onlineLogs.onInitAPI()
    onlinePlay = require("scripts/onlinePlay")
end


return onlineLogs