/* === Global Configuration === */
let playerVersion = "2.6.4";
let apiUrl = "https://api.onedisplay.se";
let cdnUrl = "https://cdn.onedisplay.se";
//apiUrl = "http://api.onedisplay.local";
//cdnUrl = "http://cdn.onedisplay.local";
var b2bcontrol;
var preview;

var pairingObject = null;
var diagnosticsObject = null;
var playerObject = null;
var statisticsObject = null;
var debugObject = null;
var layoutObject = null;
var fileManager = null;

var urlParams = new URLSearchParams(window.location.search);
var playerPreview = urlParams.get('preview');
var playerPreviewKey = urlParams.get('previewKey');

(function () {
	  const originalConsole = {
	    log: console.log,
	    error: console.error,
	    warn: console.warn,
	    info: console.info
	  };

	  function interceptConsole(method, ...args) {
		    // Format the message
		    const message = args.map(arg => {
		        if (arg instanceof Event) {
		            // Convert the event to a more readable format
		            return JSON.stringify(
		                {
		                    type: arg.type,
		                    eventPhase: arg.eventPhase,
		                    isTrusted: arg.isTrusted,
		                    timeStamp: arg.timeStamp,
		                },
		                null,
		                2
		            );
		        } else if (typeof arg === 'object') {
		            return JSON.stringify(arg, null, 2);
		        }
		        return arg;
		    }).join(' ');

		    // Call your debugLog function
		    if (debugObject !== null && typeof debugObject.add === 'function') {
		        debugObject.add(method + " > " + message);
		    }

		    // Output to the original console
		    //originalConsole[method].apply(console, args);
		}

	  // Override console functions
	  console.log = (...args) => interceptConsole("log", ...args);
	  console.error = (...args) => interceptConsole("error", ...args);
	  console.warn = (...args) => interceptConsole("warn", ...args);
	  console.info = (...args) => interceptConsole("info", ...args);

	  // Capture JavaScript errors
	  window.addEventListener("error", (event) => {
	    interceptConsole("error", `Error: ${event.message} at ${event.filename}:${event.lineno}:${event.colno}`);
	  });

	  // Capture unhandled promise rejections
	  window.addEventListener("unhandledrejection", (event) => {
	    interceptConsole("error", `Unhandled Promise Rejection: ${event.reason}`);
	  });

	})();

/*if (!String.prototype.padStart) {
    String.prototype.padStart = function (targetLength, padString) {
        targetLength = Math.max(0, targetLength - this.length);
        padString = padString || '0';
        return (new Array(targetLength + 1).join(padString) + this;
    };
}*/

function getStoredValue(key) {
	return localStorage.getItem(key);
}

function setStoredValue(key, value) {
	localStorage.setItem(key, value);
}

function removeStoredValue(key) {
	localStorage.removeItem(key);
}

function getDeviceID() {
	let deviceID = getStoredValue('deviceID');
    if (!deviceID) {
        deviceID = Math.random().toString(36).substr(2, 6).toUpperCase();
        setStoredValue('deviceID', deviceID);
    }
    
    
    return deviceID;
}

function getScreenKey() {
	let screenKey = getStoredValue('screenKey');
	if(playerPreview && playerPreviewKey) {
		screenKey = playerPreviewKey;
	}
    return screenKey;
}

/* === Start-up: initialize pairing (and thus the player) on DOM ready === */
document.addEventListener("DOMContentLoaded", () => {
  fileManager = new OneDisplayFileManager();
  debugObject = new OneDisplayDebugger();
  
  if(playerPreview) {
	console.log("Running in preview mode")
	pairingObject = new OneDisplayPreview(apiUrl);
	pairingObject.start();
  } else {
	pairingObject = new OneDisplayPairing(apiUrl);
	pairingObject.start()
  }

  if(typeof window.tizen !== 'undefined') {
	b2bcontrol = window.b2bapis.b2bcontrol;
  }
  
  preview = document.querySelector('#preview_box');
  
});