local template = require "resty.template" 
local auth = require('framework.auth')
local handle = require('framework.handle')
local lfs = require("lfs")
local proxy = require("core.proxy")

local path =  proxy['config']

-- чтение файла

local function read_file()
   local file = io.open(path) or error("Не могу открыть file: " .. path)
   local content = file:read("*a") or error("Не могу прочитать " .. path)
   file:close()
   return content
end

-- запись файла

local function write_file(content)
	file = io.open(path,'w+')
   local result = file:write(content) or error("Не могу записать " .. path)
   file:close()
   proxy.restart()
   return result
end

local function render() 
	local view = template.new("config.html", "layout.html")
	view.title     = "Настройки прокси-сервера"
	view.data = read_file()
	view:render()
end

local request = {
    POST = function()  
		ngx.req.read_body()	
		local args, err = ngx.req.get_post_args()
		if args['config'] then
			write_file(args['config'])
		end
		render()
    end,   
    GET = function()
		local req = ngx.req.get_uri_args()        
		render()
    end
}

if auth.session() then
	ngx.say(handle(request))
end
