-- 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 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")
local ej = require("ej")

local db = require(global_cfg.db)

setfenv(1, {}) 

local globals = {}

function add(summary, field, type)
    -- item 140
    local key
    -- item 59
    type = type or ""
    -- item 63
    if type == "" then
        -- item 66
        key = field
    else
        -- item 58
        key = field .. "-" .. type
    end
    -- item 60
    local old = summary[key] or 0
    -- item 61
    summary[key] = old + 1
end

function add_amount(summary, key, record)
    -- item 175
    local currency = record.currency
    local total = record.total
    -- item 177
    log.info("add_amount: "
     .. key .. " "
     .. tostring(currency)
     .. " "
     .. tostring(total)
    )
    -- item 169
    local accum = summary[key] or {}
    -- item 174
    local amount = accum[currency] or 0
    local count = accum.count or 0
    -- item 176
    accum.count = count + 1
    accum[currency] = amount + tonumber(total)
    -- item 170
    summary[key] = accum
end

function get_paying()
    -- item 205
    local all_users = db.user_get_all()
    -- item 209
    local paying = 0
    for _, user in ipairs(all_users) do
        -- item 206
        if is_paying_user(user) then
            -- item 210
            paying = paying + 1
        end
        -- item 232
        fiber.yield()
    end
    -- item 211
    return paying
end

function get_ref(event)
    -- item 104
    local ref = utils.get_host_name(event.referer)
    local me = global_cfg.my_domain
    local me2 = global_cfg.my_ip
    -- item 105
    if (((ref) and (not (ref == ""))) and (not (ref == me))) and (not (ref == me2)) then
        -- item 110
        return ref
    else
        -- item 116
        return nil
    end
end

function get_snapshot()
    local _sw1260000_ = 0
    -- item 80
    local snap = {}
    -- item 123
    snap.drakon = 0
    snap.free = 0
    snap.folders = 0
    snap.mind = 0
    snap.users = db.user_count()
    snap.sessions = db.session_count()
    snap.spaces = db.space_count()
    snap.items = db.item_count()
    --snap.paying = get_paying()
    -- item 233
    local folders = db.folder_get_all()
    for _, folder in ipairs(folders) do
        -- item 136
        local fdata = folder[3]
        -- item 186
        if fdata then
            -- item 1260000
            _sw1260000_ = fdata.type
            -- item 1260001
            if _sw1260000_ == "drakon" then
                -- item 137
                snap.drakon = snap.drakon + 1
            else
                -- item 1260002
                if _sw1260000_ == "free" then
                    -- item 138
                    snap.free = snap.free + 1
                else
                    -- item 1260003
                    if _sw1260000_ == "folder" then
                        -- item 139
                        snap.folders = snap.folders + 1
                    else
                        -- item 1260004
                        if _sw1260000_ == "mind" then
                            -- item 190
                            snap.mind = snap.mind + 1
                        end
                    end
                end
            end
        end
        -- item 141
        fiber.yield()
    end
    -- item 81
    return snap
end

function get_yesterday()
    -- item 22
    local yesterday = os.time() - 3600 * 24
    -- item 21
    return yesterday
end

function is_paying_user(user)
    -- item 217
    local user_data = user[3]
    -- item 218
    if user_data.license then
        -- item 223
        local license_data = db.license_get(
        	user_data.license
        )
        -- item 224
        if ((license_data) and (license_data.active)) and (license_data.agreement_id) then
            -- item 228
            local adata = db.agreement_get(
            	license_data.agreement_id
            )
            -- item 229
            if (adata) and (adata.state == "active") then
                -- item 222
                return true
            else
                -- item 221
                return false
            end
        else
            -- item 221
            return false
        end
    else
        -- item 221
        return false
    end
end

function summarize(rows)
    -- item 36
    local summary = {}
    local events = {}
    local refs = {}
    local payments = {}
    local raw_payments = {}
    local completes = {}
    for _, event in ipairs(rows) do
        -- item 38
        local data = event.data
        local type = data.event_type
        -- item 39
        if type then
            -- item 42
            add(events, type, "")
            -- item 440001
            if type == "create_session" then
                -- item 120
                local ref = get_ref(data)
                -- item 117
                if ref then
                    -- item 121
                    add(events, "visit", "")
                    -- item 70
                    add(refs, ref, "")
                end
            else
                -- item 440002
                if type == "create_user" then
                    -- item 62
                    add(events, type, data.src)
                else
                    -- item 440003
                    if type == "payment" then
                        -- item 182
                        table.insert(
                        	raw_payments,
                        	data
                        )
                        -- item 179
                        add_amount(payments, type, data)
                    else
                        -- item 440004
                        if type == "payment_completed" then
                            -- item 185
                            table.insert(
                            	completes,
                            	data
                            )
                        end
                    end
                end
            end
        end
        -- item 52
        fiber.yield()
    end
    -- item 51
    summary.events = events
    summary.refs = refs
    summary.payments = payments
    summary.raw_payments = raw_payments
    summary.completes = completes
    -- item 37
    return summary
end

function summarize_core(day)
    -- item 25
    if ej.summary_exists(day) then
        
    else
        -- item 16
        local events = ej.get_events(day)
        -- item 28
        local summary = summarize(events)
        -- item 75
        summary.snapshot = get_snapshot()
        -- item 23
        ej.save_summary(
        	day,
        	summary
        )
        -- item 24
        log.info("saved summary for day "
         .. tostring(day))
    end
end

function summarize_day(day)
    -- item 158
    local action = function()
    	summarize_core(day)
    end
    -- item 153
    local ok, err = pcall(action)
    -- item 154
    if ok then
        
    else
        -- item 157
        log.error("summarize_today failed "
          .. tostring(err))
    end
end

function summarize_yesterday()
    -- item 150
    local action = function()
    	local day = get_yesterday()
    	summarize_core(day)
    end
    -- item 10
    local ok, err = pcall(action)
    -- item 71
    if ok then
        
    else
        -- item 74
        log.error("summarize_today failed "
          .. tostring(err))
    end
end


return {
	summarize_yesterday = summarize_yesterday,
	summarize_day = summarize_day
}
