/**
 * Component to render data for not conserved assets
 * @class NotConserved
 */
export class NotConserved {
    biblioElements = [];
    /**
     * @param {object} data
     */
    set data(data) {
        this._data = data;
    }

    async render() {
        return `
        <div class="container px-4 pt-4">
            <p class="p-2">
                <span class="icon has-text-link">
                    <i class="fa fa-tag"></i>
                </span>
                <strong>Denominazione:</strong> ${this._data.denomination}
            </p>
            <p class="p-2">
                <span class="icon has-text-link">
                    <i class="fa fa-hourglass"></i>
                </span>
                <strong>Periodo:</strong> ${this._data.period}
            </p>
            <p class="p-2">
                <span class="icon has-text-link">
                    <i class="fa fa-map"></i>
                </span>
                <strong>Località generica:</strong> ${this._data.genericLocation}
            </p>
            <p class="mt-4 pl-2 pr-5">
                <strong class="pb-3">Descrizione</strong></br>
                ${this._data.shortDescription}
            </p>
            <p class="mt-4 pl-2 pr-5">
                <span class="icon has-text-link">
                    <i class="fa fa-book"></i>
                </span>
                <strong>Bibliografia:</strong> ${await this.biblio(this._data.id)}
            </p>
            <div class="notification is-light mx-3 mt-4 mb-0 p-2 is-hidden" data-biblio-target="biblio"></div>
            <p class="p-2 mb-4">
                <strong>Autore scheda:</strong> ${this._data.author}
            </p>
        </div>`;
    }

    renderImages() {
		let content = `<div class="content has-text-centered">
			<p class="is-size-5 mt-3">Immagini</p>`;
		content += `
			<div style="max-width: 70%; margin: 0 auto">
				<p class="is-size-6 has-text-centered">Cliccare sull'immagine per aprire la gallery</p>
				<figure class="is-relative is-clickable has-text-centered" id="not-conserved-gallery">
					<img src="img/${this.images[0].filename}" width="300"/>
					<div class="icon overlay is-flex is-justify-content-center is-align-items-center">
						<i class="is-flex fa fa-2x fa-play-circle"></i>
					</div>
				</figure>
			</div>
		</div>`;

        return content;
    }
    /**
     * @param {HTMLElement} imageContainer
     * @param {Function} gallery
     */
    async setImages(imageContainer, gallery) {
        //let record = await this.fetchData(`${window.API_URL}/not_conserved/${this._data.id}`)

        if (this._data.images.length) {
            this.images = this._data.images;
            imageContainer.innerHTML = this.renderImages();
            gallery('not-conserved-gallery', this.images);
        } else
            imageContainer.innerHTML = '<p class="has-text-centered">Nessuna risorsa visuale disponibile</p>';
    }

    async renderDocs() {
        let record = await this.fetchData(`${window.API_URL}/not_conserved/${this._data.id}`);

        this.documentation = record.documents.filter(d => d.type === 'documentazione')
        this.publications = record.documents.filter(d => d.type === 'pubblicazione');

        let content = `
            <div class="has-bottom-border">
                <div class="p-2">
                    <table class="p-4 table is-fullwidth is-striped">
                        <thead>
                            <tr><th colspan=3 class="p-2 has-text-centered is-size-5">Documentazione di archivio</th>
                            <tr><th>Titolo</th><th>Luogo di conservazione</th><th>Download</th></tr>
                        </thead>
                        <tbody>
            `;

		for (const doc of this.documentation) {
			content += `
				<tr><td>${doc.title}</td><td>${doc.conservationPlace}</td><td><a class="button is-link has-text-white" href="docs/${doc.filename}">
                    <i class="fa fa-download mr-2"></i> PDF
                </a></td></tr>
			`;
		}
        if (this.publications.length) {
            content += `
                    </tbody>
                    <thead>
                        <tr><th colspan=3 class="p-2 has-text-centered is-size-5">Pubblicazioni del progetto Carta Archeologica</th>
                        <tr><th>Titolo</th><th>Autori</th><th>Download</th></tr>
                    </thead>
                    <tbody>
            `;
            for (const doc of this.publications) {
                content += `
                    <tr><td>${doc.title}</td><td>${doc.authors}</td><td><a class="button is-link has-text-white" href="docs/${doc.filename}">
                        <i class="fa fa-download mr-2"></i> PDF
                    </a></td></tr>
                `;
            }
        }
		content += `
                </tbody>
                </table>
                </div>
            </div>
        `;

        if (!this.publications.length && !this.documentation.length) {
            content = '<p class="has-text-centered">Nessun documento disponibile.</p>';
        }

        return content;
    }

    async biblio(recordId) {
        let record = await this.fetchData(`${window.API_URL}/not_conserved/${recordId}`);

        let citations = '';

        if (record.bibliography.length) {
            record.bibliography.forEach(record => {
                citations += `
                    <span class="is-clickable is-capitalized has-text-link"
                        data-action="click->biblio#open"
                        id="cit-${record.id}">
                        ${record.citation.toLowerCase().trim()}</span>`;

                citations += record.pages?.length ? `, ${record.pages};` : ';';
                
                this.biblioElements.push(`
                    <div class="p-2 mt-2" id="ref-${record.id}">
                        <p class="p-3">${record.reference}</p>
                    </div>
                    `
                );
            });
        }

        return citations.trim().slice(0, -1);
    }

    getReference(id) {
        return this.biblioElements.find(ref => {
            let regex = new RegExp('ref-'+id+'"');
            return ref.match(regex);
        });
    }

    async fetchData(url) {
        return await fetch(url).then(res => res.json());
    }
}
