'use strict';
export const BASE_URL = 'http://dataspace.ispc.cnr.it';
const RES_ENDPOINT = '/resources/';
/**
 * @todo Report shapes??
 */
export const OBJECT_ORDER = {
    "Object Type" : null,
    "Object ID" : null,
    "Object Excavation code" : null,
    "Object Chronology" : null,
    "Object Era" : null,
    "Object Geographical Context of Discovery" : null,
    "Object Dimensions" : null,
    "Object Material" : null,
    "Object Description" : null,
    "Object Conservation State" : null,
    "Object Reused?" : null,
    "Object Project" : null,
    "Object Compiler" : null,
    "Object Bibliography" : null,
};
/*
export const SAMPLE_ORDER = {
};
*/
/**
 * @todo Query report links to determine resource type?
 * @param {int} max Max number of resources to list
 *                  (randomly selected)
 * 
 * @returns {Array} An array with selected resource links
 */
export async function fetchResourceList(max = 20)
{
    // TODO Errors!!
    const list = await fetch(`${BASE_URL}${RES_ENDPOINT}`)
        .then(res => res.json())
        .catch();
    // Arbitrary slice...
    return list['ldp:contains'].slice(100, max + 100);
}
/**
 * Create links list
 * @param {string[]} links The fetched resource links
 * @param {string} id The ID of the UL element
 * @param {string} replace The string that should replace loalhost...
 * 
 * @return {void}
 */
export function createLinks(links, id, replace)
{
    for (const link of links) {
        const item = document.createElement('li');
        item.innerHTML = 
            `
                ${link.substring(link.lastIndexOf('/') + 1)}
            `;
        document.querySelector(`#${id}`).appendChild(item);
    }
}
/**
 * Fetch JSON report...
 * @param {string} uuid The resource's UUID in Arches
 * @param {string} format Either 'json' or 'arches-json'
 * 
 * @return {object}
 */
export async function fetchReport(uuid, format='json')
{
    // TODO Errors!!
    const jsonRep =
        await fetch(`${BASE_URL}${RES_ENDPOINT}${uuid}?format=${format}&indent=2`)
        .then(res => res.json())
        .catch();
    return jsonRep;
}
export function printReport() {
    document.querySelector('#print').addEventListener('click', () => {
        window.print();
    });
}
export function attachMap(coordinates, htmlId = 'map') {
    const map = L.map(htmlId).setView(coordinates, 13);
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);
    L.marker(coordinates).addTo(map);
    /*
        .bindPopup('A pretty CSS3 popup.
 Easily customizable.')
        .openPopup();
    */
}
/**
 * @todo Use TS to define object shape
 * @param {object} resource The resource object (Arches JSON!)
 *
 * @return {string[]}
 */
export function getImageSrc(resource) {
    // TODO hardcoded...
    const filesUri = `${BASE_URL}/files/uploadedfiles/`;
    //let key = Object.keys(resource.tiles[11].data)[0];
    // TODO don't filter this array, populate another one
    let arr = resource.tiles
        .filter(tile => { 
            let key = Object.keys(tile.data)[0]
            return Array.isArray(tile.data[key]);
        }).filter(o => {
            let key = Object.keys(o.data)[0]
            return Object.keys(o.data[key][0]).includes('file_id')
        });
    let fileNames = [],
        dataObjects = [];
    arr.forEach(d => dataObjects.push(d.data));
    dataObjects.forEach(e => {
        e[Object.keys(e)[0]].forEach(o => {
            fileNames.push(filesUri + o.name)
        });
    });
    return fileNames;
}
/**
 * Fetch file blob (CORS...)
 * @todo
 * 
 * @param {string} fileUri The file's URI in Arches
 * 
 * @return {object}
 */
//export async function fetchFileBlob(fileUri);
/**
 * Query report links to determine
 * resource instance type...
 */