#!/usr/bin/lua

local vouchera = require('voucher.vouchera')
local utils = require('voucher.utils')
local uci = require('uci')
local json = require 'luci.jsonc'

local uci_cursor = uci.cursor()
local arguments
local action
local context

captive_portal = {}

vouchera.init()

captive_portal.activate = function(code, mac)
    local res = vouchera.activate(code, mac)
    if res then
        print('Voucher activated!')
        return true
    else
        return nil, "Invalid voucher code '" .. code .. "' or invalid MAC '" .. mac .. "'"
    end
end

-- Checks if the mac of the given context is allowed to browse.
captive_portal.is_mac_authorized = function(mac)
    if vouchera.is_mac_authorized(mac) then
        print('true')
        return true
    else
        print('false')
        os.exit(1)
    end
end

local function _list_by_status(status)
    for _, voucher in pairs(vouchera.vouchers) do
        if voucher.status() == status then
            print(voucher.tostring())
        end
    end
    return true
end

captive_portal.list_available = function()
    return _list_by_status('available')
end

captive_portal.list_active = function()
    return _list_by_status('active')
end

captive_portal.list_expired = function()
    return _list_by_status('expired')
end

-- List all vouchers
captive_portal.list = function()
    for _, voucher in pairs(vouchera.vouchers) do
        print(voucher.tostring())
    end
    return true
end

captive_portal.deactivate = function(id)
    return vouchera.deactivate(id)
end

captive_portal.invalidate = function(id)
    return vouchera.invalidate(id)
end

captive_portal.add = function(name, duration_m, activation_deadline)
    if type(duration_m) == "string" then
        duration_m = tonumber(duration_m)
    end
    local qty = 1
    res, msg = vouchera.create(name, qty, tonumber(duration_m), tonumber(activation_deadline))
    if res ~= nil then
        local voucher = vouchera.get_by_id(res[1].id)
        print(voucher.tostring())
        os.exit(0)
    else
        print(msg)
        os.exit(1)
    end
end

captive_portal.show_authorized_macs = function()
    for _, voucher in pairs(vouchera.vouchers) do
        if voucher.is_active() then
            print(voucher.mac)
        end
    end
    return true
end

-- if is main
if debug.getinfo(2).name == nil then
    local arguments = { ... }
    local action = table.remove(arguments, 1)
    local context = arguments
    local f = captive_portal[action]
    if f ~= nil then
        res, msg = f(unpack(context))
        if not res then
            print(msg or 'error')
            os.exit(1)
        end
    else
        print("invalid command: " .. tostring(action))
    end
end

return captive_portal
