import { emit } from '../../../utilities/emit.js';
import { ready } from '../../../utilities/ready.js';

customElements.define('ajax-html', class extends HTMLElement {

	// Initialize on connect
	connectedCallback () {
		ready(this);
	}

	// Initialize the component
	readyInit () {

		// Don't run if already initialized
		if (this.hasAttribute('is-ready')) return;

		// Get attributes
		const eventNames = this.getAttribute('event-name')?.split(',') || [];
		this.eventUID = this.getAttribute('event-uid')?.split(',') || [];
		if (!eventNames.length || !this.id) return;

		// Listen for events
		for (let eventName of eventNames) {
			document.addEventListener(eventName, (event) => {
				this.updateHTML(event, this);
			});
		}

		// Ready
		emit(this, 'ajax-html', 'ready');
		this.setAttribute('is-ready', '');
	}

	async updateHTML (event, instance) {

		// Only run if event has the correct type
		if (this.eventUID.length && !this.eventUID.includes(event.detail?.uid)) return;

		try {

			// Get the page
			let request = await fetch(location.href);
			if (!request.ok) throw request;
			let response = await request.text();

			// Convert to HTML
			let parser = new DOMParser();
			let html = parser.parseFromString(response, 'text/html');

			// Get the updated HTML element
			let newElem = html.querySelector(`#${instance.id}`);
			if (!newElem) return;

			// Replace it in the HTML
			instance.replaceWith(newElem);

		} catch (error) {
			console.warn('Unable to update HTML');
		}

	}

});
