local sgmatch = string.gmatch
local ogetenv = os.getenv

local ngx_handle = require 'bin.scaffold.nginx.handle'
local ngx_config = require 'bin.scaffold.nginx.config'
local ngx_conf_template = require 'bin.scaffold.nginx.conf_template'


local Lor = {}

function Lor.nginx_conf_content()
    -- read nginx.conf file
    local nginx_conf_template =  ngx_conf_template.get_ngx_conf_template()

    -- append notice
    nginx_conf_template = [[
#generated by `lor framework`
    ]] .. nginx_conf_template

    local match = {}
    local tmp = 1
    for v in sgmatch(nginx_conf_template , '{{(.-)}}') do
        match[tmp] = v
        tmp = tmp + 1
    end

    for _, directive in ipairs(match) do
        if ngx_config[directive] ~= nil then
            nginx_conf_template = string.gsub(nginx_conf_template, '{{' .. directive .. '}}', ngx_config[directive])
        else
            nginx_conf_template = string.gsub(nginx_conf_template, '{{' .. directive .. '}}', '#' .. directive)
        end
    end

    return nginx_conf_template
end

function new_handler()
    local necessary_dirs ={ -- runtime nginx conf/pid/logs dir
        tmp = 'tmp',
        logs = 'logs'
    }
    local env = ogetenv("LOR_ENV") or 'dev'
    return ngx_handle.new(
        necessary_dirs,
        Lor.nginx_conf_content(),
        "conf/nginx-" .. env .. ".conf"
    )
end

function Lor.start()
    local env = ogetenv("LOR_ENV") or 'dev'

    local ok, handler = pcall(function() return new_handler() end)
    if ok == false then
        print("ERROR:Cannot initialize handler: " .. handler)
        return
    end

    local result = handler:start(env)
    if result == 0 or result == true or result == "true" then
        if env ~= 'test' then
            print("app in " .. env .. " was succesfully started on port " .. ngx_config.PORT)
        end
    else
        print("ERROR: Could not start app on port " .. ngx_config.PORT)
    end
end


function Lor.stop()
    local env = ogetenv("LOR_ENV") or 'dev'

    local handler = new_handler()
    local result = handler:stop(env)

    if env ~= 'test' then
        if result == 0 or result == true or result == "true" then
            print("app in " .. env .. " was succesfully stopped.")
        else
            print("ERROR: Could not stop app (are you sure it is running?).")
        end
    end
end

function Lor.reload()
    local env = ogetenv("LOR_ENV") or 'dev'

    local handler = new_handler()
    local result = handler:reload(env)

    if env ~= 'test' then
        if result == 0 or result == true or result == "true" then
            print("app in " .. env .. " was succesfully reloaded.")
        else
            print("ERROR: Could not reloaded app.")
        end
    end
end

return Lor
