/**
* SYSout JS - Basic JavaScript 2 JAVA Error Logger - build upon useful parts from stumble.js
* 
* @Author Tim Wahrendorff
* @version 1.1
*/

(function(window) {
	
    var errors = [];
    var startTimer = 0;
	var batchTimer = 2000;
	var verbose = false;
	var currentTime = new Date().getTime();
	
	
    var onErrorFunction = function(evt){
    
    	// do not log Javascript Errors, that are obviously not from our application
    	const stack = evt.error.stack || '';
		const isExtensionError = stack.includes('chrome-extension://') || stack.includes('moz-extension://');
		const isConsoleError = stack.includes('<anonymous>') && !stack.includes('at Object.InjectedScript.');
		const isApplicationError = !isExtensionError && !isConsoleError;
      
		if(!isApplicationError){
			console.error('There have been an application unrelated Javascript error.', evt.error);
			return;
		}
		
		if ( verbose ) {
	        console.error( "sysoutJS arguments", arguments );
	        console.error( "sysoutJS evt", evt );
	    }
		function sendError() {
			var location = "" + window.location;
			var CONTEXT_PATH = "/" + location.split("/")[3]
			/**
			 * TODO: find better solution for no CONTEXT_PATH
			 */
			if (CONTEXT_PATH == '/pages'
				|| CONTEXT_PATH == '/a'
				|| CONTEXT_PATH == '/pub') {
				CONTEXT_PATH = "";
			}
			var url = CONTEXT_PATH+"/jsonservicecall?sysoutjs";
	        if ( !url ) {
	            console.warn( "Unable to POST error, no url set", url  );
	            return;
	        }
	        var xhrObj = new window.XMLHttpRequest();
	        xhrObj.open( "POST", url, true );
	        xhrObj.setRequestHeader( "Content-type", "application/json" );
	        xhrObj.onreadystatechange = function() {//Call a function when the state changes.
	            if ( xhrObj.readyState !== 4 && xhrObj.status !== 200 ) {
	                console.error( "Unable to post error to the url: '", url, "', in other words... there was an error with this error :)" );
	            }
	        };
	        xhrObj.send( window.JSON.stringify( {
	            sysoutjs: errors
	        } ) );
	    }
	    
	    function isTimeToSend() {
			var currentTime = new Date().getTime();
	        return ( currentTime - startTimer ) >= batchTimer;
	    } 
	
		errors.push({
            type: "error",
            message: evt.error.message,
            at: evt.filename+":"+evt.lineno+ ":"+evt.colno,
            url: window.location.href,
            stack: evt.error.stack,
            clientInformation:  evt.currentTarget.doNotTrack ? '' : evt.currentTarget.clientInformation.userAgent
        });
	    if ( !startTimer ) {
	        startTimer = currentTime;
	        window.setTimeout( function() {
	            var time;
	            if ( isTimeToSend() ) {
	                time = startTimer;
	                startTimer = 0;
	                sendError();
	                errors = [];
	            }
	        }, batchTimer );
	    }
	    return true;
	}
    window.addEventListener("error", onErrorFunction);
    if ( verbose ) console.info("SysoutJS Intialised!");
}(window));