-- Autogenerated with DRAKON Editor 1.32
local table = table
local insert = table.insert
local string = string
local pairs = pairs
local ipairs = ipairs
local type = type
local pcall = pcall
local print = print
local tostring = tostring
local tonumber = tonumber
local tonumber64 = tonumber64
local math = require("math")

local global_cfg = global_cfg

local clock = require("clock")
local log = require("log")
local digest = require("digest")
local fiber = require("fiber")
local io = require("io")
local os = require("os")
local utf8 = require("lua-utf8")

local json = require("json")

local utils = require("utils")

setfenv(1, {}) 

local globals = {}

function get_date_string(date_time)
    -- item 114
    return date_time:sub(1, 10)
end

function get_events(day)
    -- item 191
    local date_string = time_to_day(day)
    -- item 190
    local filename = make_ej_filename(date_string)
    -- item 177
    local result = {}
    -- item 154
    local file = io.open(filename, "rb")
    -- item 170
    if file then
        -- item 179
        file:close()
        for line in io.lines(filename) do
            -- item 176
            local item = parse_line(line)
            -- item 180
            table.insert(
            	result,
            	item
            )
        end
    end
    -- item 178
    return result
end

function get_now()
    -- item 212
    local t = clock.time()
    local fraction = t - math.floor(t)
    local fs
    -- item 213
    if fraction == 0 then
        -- item 216
        fs = "0000"
    else
        -- item 217
        fs = tostring(fraction):sub(3, 6)
    end
    -- item 218
    return os.date("%Y-%m-%dT%H:%M:%S", t) .. "." .. fs
end

function get_summaries()
    -- item 197
    local cmd = "ls " .. global_cfg.journal_dir
     .. "/sum*.json 2>/dev/null"
    -- item 196
    local handle = io.popen(cmd)
    local ls = handle:read("*all")
    handle:close()
    -- item 198
    local names =  utils.split(ls, "\n")
    -- item 199
    local path_start = global_cfg.journal_dir
      .. "/sum"
    local date_start = #path_start + 1
    local date_end = #path_start + 10
    -- item 200
    local result = {}
    for _, line in ipairs(names) do
        -- item 204
        local date_str = line:sub(
        	date_start,
        	date_end
        )
        -- item 205
        local content = utils.read_all_bytes(line)
        local data = json.decode(content)
        -- item 207
        local item = {
        	date = date_str,
        	data = data
        }
        -- item 206
        table.insert(
        	result,
        	item
        )
    end
    -- item 201
    return result
end

function info(type, data)
    -- item 36
    local log_it = function()
    	log_event(type, data)
    end
    -- item 92
    local status, err = pcall(log_it)
    -- item 88
    if status then
        
    else
        -- item 91
        print(
        	"ej.info failed: "
        	.. tostring(type) .. " "
        	.. tostring(err)
        )
    end
end

function init()
    
end

function log_event(type, data)
    -- item 28
    local fields = {
    	event_type = type
    }
    -- item 29
    if data then
        for key, value in pairs(data) do
            -- item 34
            fields[key] = value
        end
    end
    -- item 35
    local timestamp = get_now()
    write_event(timestamp, fields)
end

function make_ej_filename(date_string)
    -- item 161
    local path = global_cfg.journal_dir .. "/"
      .. date_string .. ".txt"
    -- item 162
    return path
end

function make_summary_filename(day)
    -- item 145
    local date_string = time_to_day(day)
    -- item 147
    local path = global_cfg.journal_dir .. "/sum"
      .. date_string .. ".json"
    -- item 148
    return path
end

function parse_line(line)
    -- item 186
    local space_pos = line:find(" ")
    -- item 187
    local timestamp_str = line:sub(1, space_pos - 1)
    local data_str = line:sub(space_pos + 1)
    -- item 188
    return {
    	timestamp = tonumber64(timestamp_str),
    	data = json.decode(data_str)
    }
end

function save_summary(day, data)
    -- item 86
    local save = function()
    	save_summary_core(
    		day,
    		data
    	)
    end
    -- item 83
    if pcall(save) then
        
    else
        -- item 87
        log.error(
            "Error saving summary for day: "
            .. tostring(day)
        )
    end
end

function save_summary_core(day, data)
    -- item 138
    local filename = make_summary_filename(
    	day
    )
    -- item 139
    local content = json.encode(data)
    -- item 75
    utils.write_all_bytes(
    	filename,
    	content
    )
end

function summary_exists(day)
    -- item 135
    local filename = make_summary_filename(
    	day
    )
    -- item 134
    local file = io.open(filename, "rb")
    -- item 131
    if file then
        -- item 189
        file:close()
        -- item 136
        return true
    else
        -- item 137
        return false
    end
end

function time_to_day(time)
    -- item 168
    local date_string = os.date("%Y-%m-%d", time)
    -- item 169
    return date_string
end

function write_event(timestamp, fields)
    -- item 115
    local date_string = get_date_string(timestamp)
    -- item 98
    if globals.log_date == date_string then
        
    else
        -- item 116
        if globals.log_handle then
            -- item 119
            globals.log_handle:close()
            globals.log_handle = nil
        end
        -- item 120
        local path = make_ej_filename(date_string)
        -- item 121
        globals.log_date = date_string
        -- item 122
        globals.log_handle = io.open(path, "a+b")
    end
    -- item 123
    local serialized = json.encode(fields)
    -- item 124
    globals.log_handle:write(tostring(timestamp))
    globals.log_handle:write(" ")
    globals.log_handle:write(serialized)
    globals.log_handle:write("\n")
    -- item 125
    globals.log_handle:flush()
end


init()

return {
	info = info,
	save_summary = save_summary,
	summary_exists = summary_exists,
	get_events = get_events,
	get_summaries = get_summaries,
	get_now = get_now
}
