/* eslint-disable */

var loginMessageElem = document.getElementById('login-info');
var oldLoginMessageElem = document.getElementById('old-login-info');
var outageMessageElem = document.getElementById('outage-message');
var foldElem = document.getElementById('fold');
var redirectInfoElement = document.getElementById('redirect-info');
var logoutElement = document.getElementById('logout');

var version = '2.1.3';

var reopenTimeout = 1000 * 60 * 60 * 2; // 2 hours

var featureToggles = {};

var root = '';
function isStandalone() {
	return navigator.standalone || (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches);
}

function sessionDetails() {
	return {
		userAgent: navigator.userAgent,
		version: version,
		standalone: isStandalone(),
	};
}

function xhr(method, url, body, setHeader, c) {
	var request = new XMLHttpRequest();
	request.onreadystatechange = function () {
		request.readyState ^ 4 || (c && c(this));
	};
	request.withCredentials = true;
	request.open(method, url, c);
	setHeader && setHeader(request);
	request.send(body);
	return request;
}

function clearLocalStorageAndLogout() {
	window.localStorage.clear();
	window.location.reload();
}

function setUpIdleLogout() {
	/*
	 * this function clears the localStorage cache and reloads browser page
	 * after given timeout making the user login again
	 * timer is reset based on the events registered
	 * */
	var t;
	var timeOut = 3300000; //in milliseconds - 55 minutes
	var redisStoreTimeOutInterval = 300000; //in milliseconds - 5 minutes
	var redisLastStoredTime = 0;
	var lastLocation = stored('last-login');

	if (lastLocation && Date.now() - lastLocation.time > timeOut) {
		clearLocalStorageAndLogout();
	}
	window.addEventListener('load', resetTimer, true);
	var events = [
		'mousemove',
		'click',
		'scroll',
		'touchstart',
		'touchmove',
		'beforeinstallprompt',
		'sizemodechange',
		'fullscreen',
	];
	events.forEach(function (name) {
		window.addEventListener(name, resetTimer, true);
	});

	function resetTimer() {
		clearTimeout(t);
		t = setTimeout(clearLocalStorageAndLogout, timeOut);
		if (Date.now() > redisLastStoredTime) {
			localStorage.setItem('last-login', JSON.stringify({ time: Date.now() }));
			redisLastStoredTime = Date.now() + redisStoreTimeOutInterval;
		}
	}
}

function displayLoginError(message) {
	loginMessageElem.style.display = '';
	loginMessageElem.innerHTML = message;
}

function displayOldLoginError(message) {
	oldLoginMessageElem.style.display = '';
	oldLoginMessageElem.innerHTML = message;
}

function hideLoginError() {
	oldLoginMessageElem.style.display = 'none';
	loginMessageElem.style.display = 'none';
}

function hideRedirectionInfo() {
	redirectInfoElement.style.display = 'none';
}

function setJsonContentType(req) {
	req.setRequestHeader('Content-Type', 'application/json');
}

function displayOutageMessage(outageMessage) {
	if (null !== outageMessage && !['null', '', 'false', 'true'].includes(outageMessage)) {
		outageMessageElem.style.display = '';
		outageMessageElem.innerHTML = outageMessage;
	}
}

function login() {
	logoutElement.style.display = 'none';
	if (featureToggles.SSO_REDIRECT_TOGGLE) {
		redirect();
	} else {
		location.hash = '';
		loginable();
	}
}

function redirect() {
	foldElem.classList.add('show-redirect');
	xhr('GET', root + '/auth/ssoUrl', null, null, function (response) {
		if (response.status === 200) {
			hideLoginError();
			var ssoRedirectUrl = response.responseText;
			if (ssoRedirectUrl) {
				if (!location.hash.includes('logout'))
					localStorage.setItem(
						'pre-redirection-hash',
						JSON.stringify({
							hash: location.hash,
							time: Date.now(),
						})
					);
				window.location.href = ssoRedirectUrl + '&redirect_uri=' + window.location.origin;
			} else {
				foldElem.classList.remove('show-redirect');
				foldElem.classList.add('show-login');
				displayLoginError('Something went wrong. Try again, or  contact support.');
			}
		} else {
			foldElem.classList.remove('show-redirect');
			foldElem.classList.add('show-login');
			displayLoginError('Something went wrong. Try again, or  contact support.');
		}
	});
	return false;
}

function sessioned() {
	var regex = /[?&]([^=#]+)=([^&#]*)/g,
		url = window.location.href,
		params = {},
		match;
	while ((match = regex.exec(url))) {
		params[match[1]] = match[2];
	}
	if (params.code) {
		xhr(
			'POST',
			root + '/auth/login',
			JSON.stringify({
				authorizationCode: params.code,
				redirectUri: window.location.origin,
			}),
			setJsonContentType,
			function (response) {
				if (response.status === 200) {
					hideLoginError();
					hideRedirectionInfo();
					var user = jsonify(response.responseText);
					if (user) {
						foldElem.style.display = 'none';
						store('active-session', true);
						bootable({ user: user });
						window.location.href = location.origin + location.hash;
					} else {
						displayLoginError('Something went wrong. Try again, or  contact support.');
						foldElem.classList.add('show-login');
					}
				} else if (response.status === 403) {
					var error = jsonify(response.responseText);
					if (error.error === 'no_operations') {
						displayLoginError("You don't have permission to view MyInsights. Contact support.");
					}
					foldElem.classList.add('show-login');
				} else {
					displayLoginError('Something went wrong. Try again, or  contact support.');
					foldElem.classList.add('show-login');
				}
			}
		);
	} else {
		if (stored('active-session')) {
			if (navigator.onLine !== false) {
				xhr(
					'POST',
					root + '/auth/current',
					JSON.stringify({
						details: sessionDetails(),
					}),
					setJsonContentType,
					function (response) {
						if (response.status === 200) {
							var user = jsonify(response.responseText);
							if (user) {
								bootable({ user: user });
							}
							return;
						}
						redirect();
					}
				);
			} else {
				var last = stored('last-session');
				if (last) {
					if (last.user) {
						bootable({ user: last.user });
					}
				}
			}
		} else {
			if (location.hash.includes('logout')) logoutElement.style.display = 'flex';
			else redirect();
		}
	}
}

function loginable() {
	foldElem.classList.add('show-old-login');
}

function oldLogin(form) {
	xhr(
		'POST',
		root + '/auth/login',
		JSON.stringify({
			username: form.username.value,
			password: form.password.value,
			details: sessionDetails(),
		}),
		setJsonContentType,
		function (response) {
			if (response.status === 200) {
				hideLoginError();
				var user = jsonify(response.responseText);
				if (user) {
					foldElem.style.display = 'none';
					store('active-session', true);
					bootable({ user: user });
					form.reset();
				} else {
					displayOldLoginError(
						'Received an unexpected response while attempting to login, please try again. If the problem continues please contact support.'
					);
				}
			} else if (response.status === 401) {
				displayOldLoginError('The username and password that you entered did not match our records.');
			} else if (response.status === 403) {
				var error = jsonify(response.responseText);
				if (error.error === 'no_operations') {
					displayOldLoginError(
						"User is not assigned necessary permissions to view any operation data. Contact support on <a href=\'tel:+18003337899,28000\'>1-800-333-7899 ext 28000</a>"
					);
				}
			} else {
				displayOldLoginError(
					'Received an unexpected response while attempting to login, please try again. If the problem continues please contact support.'
				);
			}
		}
	);
	return false;
}

function oldSessioned() {
	if (stored('active-session')) {
		if (navigator.onLine !== false) {
			xhr(
				'POST',
				root + '/auth/current',
				JSON.stringify({
					details: sessionDetails(),
				}),
				setJsonContentType,
				function (response) {
					if (response.status === 200) {
						var user = jsonify(response.responseText);
						if (user) {
							bootable({ user: user });
						}
						return;
					}
					if (response.status === 403) {
						clearLocalStorageAndLogout();
					}
					loginable();
				}
			);
		} else {
			var last = stored('last-session');
			if (last) {
				if (last.user) {
					bootable({ user: last.user });
				}
			}
		}
	} else {
		loginable();
	}
}

function jsonify(value) {
	try {
		return JSON.parse(value);
	} catch (e) {
		return null;
	}
}

function bootable(params, retrying) {
	var lastSession = stored('last-session');
	params.user.existing = lastSession && lastSession.user && lastSession.user.username === params.user.username;
	store('last-session', {
		accessed: Date.now(),
		user: params.user,
	});
	var preRedirectionUrlHash = stored('pre-redirection-hash');
	if (location.search.includes('code')) {
		if (preRedirectionUrlHash) {
			localStorage.removeItem('pre-redirection-hash');
			location.hash = preRedirectionUrlHash.hash;
		}
		//window.location.href = location.origin + location.hash;
	}
	if (window.boot) {
		if (location.hash === '#/login' || location.hash === '#/logout') {
			// prevent login loop
			location.hash = '';
		}
		if (window.platform && platform.ios && platform.standalone) {
			var lastLocation = stored('last-location');
			if (
				lastLocation &&
				lastLocation.user === params.user.username &&
				Date.now() - lastLocation.time < reopenTimeout
			) {
				location.hash = lastLocation.pathname;
			}
		}
		analytics(params.user);
		window.boot(params);
	} else {
		if (!retrying) {
			// handle initial bootable state
		}
		setTimeout(function () {
			bootable(params, true);
		}, 100);
	}
}

xhr('GET', root + '/api/mi/feature-toggles', null, null, function (response) {
	setUpIdleLogout();
	if (response.status === 200) {
		featureToggles = jsonify(response.responseText);
		store('feature-toggles', featureToggles);
		if (featureToggles.SSO_REDIRECT_TOGGLE) {
			sessioned();
		} else {
			oldSessioned();
		}
		if (featureToggles.OUTAGE_MSG_ENABLED) {
			xhr('GET', root + '/api/mi/outage-message', null, null, function (response) {
				if (response.status === 200) {
					displayOutageMessage(response.responseText);
				} else {
					displayOutageMessage('Outage message failed to load, continue to login');
				}
			});
		}
	} else {
		oldSessioned();
	}
});

function analytics(user) {
	if (!(user.gaIgnore || /\bga-ignore\b/i.test(window.location.search))) {
		var prod = window.location.hostname === 'myinsights.gapinc.com';
		var tracking = prod ? 'UA-80650471-3' : 'UA-80650471-2';
		var config = prod
			? 'auto'
			: {
					cookieDomain: 'none',
				};
		window.ga =
			window.ga ||
			function () {
				ga.q.push(arguments);
			};
		ga.q = [];
		ga.l = +new Date();
		ga('create', tracking, config);
		ga('set', 'AppVersion', version);
		ga('set', 'dimension1', version);
		ga('set', 'dimension2', isStandalone());
		ga('send', 'pageview');
	} else {
		window.ga = function () {};
	}
}

function stored(key) {
	var value = localStorage.getItem(key);
	return value ? jsonify(value) : null;
}

function store(key, value) {
	localStorage.setItem(key, JSON.stringify(value));
}
