"use strict";

let newsletter_form;
let newsletter_input_submit;
let newsletter_feedback;
let newsletter_feedback_wait;
let newsletter_feedback_success;
let newsletter_feedback_failure;

window.addEventListener("load", function(){
	// STORE ELEMENTS //
	newsletter_form = document.getElementById("newsletter-signup-form");
	newsletter_input_submit = document.getElementById("newsletter-signup-form-submit");
	newsletter_feedback = document.getElementById("newsletter-signup-form-feedback");
	newsletter_feedback_wait = document.getElementById("newsletter-signup-form-feedback-wait");
	newsletter_feedback_success = document.getElementById("newsletter-signup-form-feedback-success");
	newsletter_feedback_failure = document.getElementById("newsletter-signup-form-feedback-failure");
	
	
	// INITIALIZE INPUTS //
	newsletter_init_submit();
});



/**
* HELPER: Initialize submit button input.
*/
async function newsletter_init_submit(){
	// REGISTER CLICK HANDLER //
	newsletter_input_submit.addEventListener("click", newsletter_submit);
}



/**
* CALLBACK: Maybe submit the form.
*/
async function newsletter_submit(){
	// SHOW WAIT FEEDBACK //
	newsletter_feedback.classList.remove("hidden", "gone");
	newsletter_form.classList.add("hidden");
	newsletter_feedback_wait.classList.remove("hidden", "gone");
	
	
	// COLLECT VALUES //
	// mail address
	const url_params = new URLSearchParams(window.location.search);
	let mail_address = url_params.get("mail_address");
	
	// verify_key
	let verify_key = url_params.get("key");
	
	
	// SEND API REQUEST //
	var xhr = new XMLHttpRequest();
	xhr.open("POST", "/api/newsletter/subscribe", true);
	xhr.setRequestHeader("Content-Type", "application/json");
	xhr.setRequestHeader("x-cookieless-csrf-protection", "42");
	xhr.send(JSON.stringify({
		mail_address: mail_address,
		verify_key: verify_key
	}));
	
	xhr.onload = function(){
		let success = true;
		
		// validate http status code
		if(xhr.status !== 200) success = false;
		
		// check response
		if(success){
			let response = null;
			try {
				response = JSON.parse(xhr.response);
			} catch(e){}
			
			if(typeof response !== "object") success = false;
			if(success && response === null) success = false;
			if(success && response.success !== true) success = false;
		}
		
		// positive feedback
		if(success){
			newsletter_feedback_wait.classList.add("gone");
			newsletter_feedback_success.classList.remove("hidden", "gone");
			return;
		}
		
		// negative feedback
		newsletter_feedback_wait.classList.add("gone");
		newsletter_feedback_failure.classList.remove("hidden", "gone");
	}
}
