// eslint-disable-next-line no-unused-vars
class Miscellaneous {

	static vsWidget = null;

	static warnings = [];
	static loggingEnabled = false;

	static ready(readyFunction) {
		const favIconLinkElement = document.createElement('link');
		favIconLinkElement.rel = "icon";
		favIconLinkElement.type = "image/x-icon";
		favIconLinkElement.href = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAA
			gCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAoVJREFUWEftlr9vEmEYx793EH5oE0oM0ARJbNJoI2GQCo2DTaWoC4lx1
			U5FE7caXFwQEzvh4OBi23+gJiaUcNKhOlhTa8KEFSphoRBwKZLYpKQU7sx7eMcPlTsqRAfe5HK53Jvn/Tzf5/s8d5T
			ROMLhHy5qADBQQI4CFAC1EqixQIUFyLOwOO5XD1NU847ODpc0IQnld52Ee0yNbwcsAm/3Ef9aE6OazWbMzt6GcGgot
			IpUKiW7rzoCkORuWlV4cWMYQlIHRyzOP9tDuVo/w+FwIBwOQaFQ8M9e710wDNM7AN/lE3g4NdSQHID9+R4K+2z/Acg
			JY6dovLqlx8gQjRoHMKlD3At9h1D5vipAAIjJLDoa189qsFuq4V2mgqOGBfpbAjmF7LsCzRC/azmn09lmwjuIRBoml
			GpJyTa0Wq1YXl7iOWiaAkXRLcJoNGqYTCaxDYvFIsrlMl86n+8BNjbedxRSEmBiwo5o9DUfhAStVqv8XVgkQ6VSKQK
			Q9yxb75C5OS/W19/0FoBklcnsikHHx89hYeGJOAeCwafY2vpIcLGz8wWlUqm3ADMzV5FIJMSgfTdhewkGAAMF/kMFL
			iIcXhXbcH7+PlZWXsqZ4vyergdRuwI2mw2RSBharZYPGI9/gt//CCxbg8FgwPb2Z+RyuT8C/TWAXq/H2loUo6NnxGn
			ZfNri4hICgcfHB7DbL4BhImIAt/sakslk4weF4+ByXUEwGITFcrouK0WJ4zqbzWJy8lLL+G6mkVRApVKB/PcJK5/Po
			1KptGREvg1GoxEejwfT01PQ6YZRKBSQTqcRi8Wwufnh+ACy3fRzI4EhF1FB6lMsy4TdAnS7X7IE3Qbsdv8A4Afbooy
			QDbB3HAAAAABJRU5ErkJggg==`;
		document.head.appendChild(favIconLinkElement);

		const basisStyleElement = document.createElement('style');
		basisStyleElement.textContent = `
			body {
				margin: 0;
				display: flex;
				flex-direction: column;
				height: 100vh;
				font-family: "Segoe UI", Verdana, Geneva, sans-serif;
 				font-size: 14px;
 				overflow: hidden;
			}

			#toolbar {
				display: flex;
				gap: 5px;
				align-items: center;
				margin-left: 8px;
				margin-right: 16px;
			}

			#warnBtnSpacer {
				flex: 1;
			}
		
			#warnBtn {
				height: 20px;
				width: 110px;
				color: red;
				display: none;
			}

			#VSWidget {
				flex: 1;
				background-color: white;
			}
			`;
		document.head.appendChild(basisStyleElement);

   	const toolbarElement = document.querySelector('#toolbar');
		if (toolbarElement) {
         const fileName = window.location.pathname.split('/').pop();
         const decodedFileName = decodeURIComponent(fileName);
         const baseName = decodedFileName.replace(/\.[^/.]+$/, ""); // removes .html, .htm, etc.

         const h3 = document.createElement("h3");
         const a = document.createElement("a");
         a.href = `docs/${baseName}.pdf`;
         a.target = "_blank";
         a.textContent = baseName;
         h3.appendChild(a);
         toolbarElement.prepend(h3);
            
         const titleText = `${baseName.slice(0,5)} - VSW SE Tutorial`;
         let titleElement = document.querySelector("title");
         if (!titleElement) {
            titleElement = document.createElement("title");
            document.head.appendChild(titleElement);
         }
         titleElement.textContent = titleText;

			const warnBtnSpacerDivElement = document.createElement('div');
			warnBtnSpacerDivElement.id = "warnBtnSpacer";
			toolbarElement.appendChild(warnBtnSpacerDivElement);

			const warnButtonElement = document.createElement('input');
			warnButtonElement.id = "warnBtn";
			warnButtonElement.type = "button";
			toolbarElement.appendChild(warnButtonElement);

			warnButtonElement.addEventListener('click', () => { Miscellaneous.showWarnings(); });

		}

		if (document.readyState !== 'loading') {
			readyFunction();
		}
		else {
			const listener = () => {
				document.removeEventListener('DOMContentLoaded', listener);
				readyFunction();
			};
			document.addEventListener('DOMContentLoaded', listener);
		}
	}

	static instantiateVSWidget(element, options) {
		const { VSWidget } = netronic.nVSW;

		const vsWidget = Miscellaneous.vsWidget = new VSWidget(element, {
			...options,

			onLogError: Miscellaneous.addWarning.bind(Miscellaneous),
			onLogWarning: Miscellaneous.addWarning.bind(Miscellaneous),
		});

		return vsWidget;
	}

	static addWarningx(args) {
		Miscellaneous.warnings.push(args);
		const warnBtn = document.getElementById("warnBtn");
		if (warnBtn) {
			warnBtn.style.display = "block";
			warnBtn.value = `${Miscellaneous.warnings.length} Warnings`;
		}
	}

   static addWarning(args) {
		if ("rethrow" in args) {
            Miscellaneous.warnings.push(
				{
					commandCounter: args.commandCounter,
					commandName: "",
					code: args.error.name,
					description: args.error.message
				}
			);
        }
		else
		   Miscellaneous.warnings.push(args);
	   
		const warnBtn = document.getElementById("warnBtn");
		if (warnBtn) {
			warnBtn.style.display = "block";
			warnBtn.value = `${Miscellaneous.warnings.length} Warnings`;
		}
	}

	static showWarnings() {
		const title = "VSW SE - Errors and Warnings";
		const keys = ["commandCounter", "commandName", "code", "description"];

		const newWindow = window.open("", "_blank");

		if (!Miscellaneous.warnings?.length) {
			newWindow.document.body.innerHTML = "<p>No data available!</p>";
		}
		else {
			let html = `
				<html>
				<head>
					<title>${title}</title>
					<style>
					body { font-family: Arial, sans-serif; background: #f9f9f9; }
					table { border-collapse: collapse; margin: 40px auto; }
					th, td { border: 1px solid #ccc; padding: 8px 14px; }
					th { background: #f0f0f0; }
					</style>
				</head>
				<body>
					<h2 style="text-align:center;">${title}</h2>
					<table>
					<thead>
						<tr>
							${keys.map(key => `<th>${key.charAt(0).toUpperCase()}${key.slice(1)}</th>`).join('')}
						</tr>
					</thead>
					<tbody>
						${Miscellaneous.warnings.map(obj =>
							`<tr>${keys.map(key => `<td>${obj[key] ?? ""}</td>`).join('')}</tr>`
						).join('')}
					</tbody>
					</table>
				</body>
				</html>
			`;
			newWindow.document.body.innerHTML = html;
			newWindow.document.close();
		}
	}

	

}     