local http_formdecode = require "net.http".formdecode;
local usermanager = require "core.usermanager";
local nodeprep = require "util.encodings".stringprep.nodeprep;
local st = require "util.stanza";
local url_escape = require "util.http".urlencode;
local render_html_template = require "util.interpolation".new("%b{}", st.xml_escape, {
	urlescape = url_escape;
});

local site_name = module:get_option_string("site_name", module.host);

local invites = module:depends("invites");
--local template_get = module:depends("invites_page").template_get;

local templatePath = module:get_option_string("invites_template_html", "html");
function template_get(filename, lang)
	local template = lang and templatePath.."/"..filename.."."..lang..".html" 
		or templatePath.."/"..filename..".html";
	return assert(module:load_resource(template):read("*a"));
end


module:depends("http");

local default_path, lang;

local function serve_webgen(event)
	local query_params = event.request.url.query and http_formdecode(event.request.url.query);
	lang = query_params and query_params.l;

	local webgen_template = template_get("webgen", lang);
	event.response.headers["Content-Type"] = "text/html; charset=utf-8";

	local webgen = render_html_template(webgen_template, {
		site_name = site_name;
	});
	return webgen;
end

module:depends("invites_register_web");

local function handle_webgen(event)
	local request, response = event.request, event.response;
	local form_data = http_formdecode(request.body);
	local username, password = form_data["username"], form_data["password"];

	event.response.headers["Content-Type"] = "text/html; charset=utf-8";

	local webgen_template = template_get("webgen", lang);
	local http_path = module:http_url("webgen", "/webgen");

	if not username or #username == 0 or not password or #password == 0 then
		return render_html_template(webgen_template, {
			site_name = site_name;
			path = http_path;
			msg_class = "alert-warning";
			message = "Please fill in all fields.";
		});
	end

	local prepped_username = nodeprep(username);
	local exists = usermanager.user_exists(prepped_username, module.host);
	local pass = usermanager.test_password(prepped_username, module.host, password);
	local allow_user = module:get_option_boolean("allow_user_invites", false);
	local allow_contact = module:get_option_boolean("allow_contact_invites", false);

	local invite;
	if exists and pass and allow_user and allow_contact then
		invite = invites.create_contact(username, true, { source = "webgen" });
	else
		return render_html_template(webgen_template, {
			site_name = site_name;
			path = http_path;
			username = username;
			msg_class = "alert-warning";
			message = "Invalid input!";
		});
	end

	if not invite then
		return 500;
	else
		event.response.headers.Location = invite.landing_page or invite.uri;
		return 303;
	end
end

module:provides("http", {
	default_path = "webgen";
	route = {
		["GET"] = serve_webgen;
		["POST"] = handle_webgen;
	};
});
