
var extents = [];
var products = [];
var files_list = [];

const form = document.querySelector('#form');
const submit_btn = document.querySelector('#submit');
const loading_map = document.querySelector('#loading_bnt');
const loading_extents = document.querySelector('#loading-extents');
const loading_products = document.querySelector('#loading-products');
const extent_input = document.querySelector('#extent-input');
const error = document.querySelector('#error');
const map_picture = document.querySelector('#map-picture');
const nb_tiles = document.querySelector('#nb_tiles');
const tiles_list = document.querySelector('#tiles-list');
const extents_list = document.querySelector('#extents-list');
const products_list = document.querySelector('#products-list');
const extents_level = document.querySelectorAll("input[type=radio][name='level']");
const bbox_ckeckbox = document.querySelector('#bbox');
const extent_buffer = document.querySelector('#extent-buffer');
const clear = document.querySelector('#clear');
const map_link = document.querySelector('#map-link');
const download_files_list = document.querySelector('#download-files-list');
const download_files = document.querySelector('#download-files');


function loading_submit(on) {
    on = on || false;
    if (on) {
        loading_map.classList.remove("hidden");
        submit_btn.classList.add("hidden");
    } else {
        loading_map.classList.add("hidden");
        submit_btn.classList.remove("hidden");
    }
}

function displayError(message) {
    message = message || false;
    if (message) {
        error.textContent = message;
        error.classList.remove("collapse");
    } else {
        error.textContent = '';
        error.classList.add("collapse");
    }
}

async function get_map(code, level, product, buffer, bbox) {
    tiles_layer = product['layer_tiles'] || 'dalles_ortho_1km';
    tiles = await eel.get_map(code, level, tiles_layer, buffer, bbox)();  // Call a Python function
    
    if (tiles.length) {
        const tile_name_prefix = [product['data_extent'], product['data_date']].join('-');
        var tile_name_sufix = '';
        if (product['data_date'] == '2015') {
            // 67-2015-0988-6877-LA93-0M20-E100.jp2  
            tile_name_sufix = ['LA93', '0M' + product['data_resolution'], 'E' + product['data_compression']].join('-');
        } else {
            // 67-2018-0988-6876-LA93-0M20-RVB.jp2  
            tile_name_sufix = ['LA93', '0M' + product['data_resolution'], product['data_type'].toUpperCase()].join('-');
        }
        nb_tiles.textContent = tiles.length
        tiles_list.innerHTML = "";
        for (var i=0, n=tiles.length; i<n; i++) {
            tile_name = [tile_name_prefix, tiles[i]['DALLE'], tile_name_sufix].join('-');
            tile_url = product['data_url'] + tile_name + '.jp2';
            tiles_list.innerHTML += '<li class="list-group-item border border-0"><a href="' + tile_url + '" class="file_link">' + tile_name + '</a></li>';
            // files_list.push({'name': tile_name, 'url': tile_url});
            files_list.push(tile_name);
        }
        var d = new Date(); 
        var image='./map.png?' + d.getMilliseconds();
        map_picture.src = image;
    } else {
        map_picture.src = './empty.png';
        nb_tiles.textContent = 0;
    }
}

function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
}

const downloadAllLinks = (links) => {
    if (links.length == 0) return;
    let delay = 100;
    for (let i=0, n=links.length; i<n; i++) {
        const link = links[i];
        link.setAttribute('download', link.getAttribute('href'));
        setTimeout(() => link.click(), delay);
        delay += 2000;
    }
}

async function get_extents(level) {
    loading_extents.classList.remove("hidden");
    extents = await eel.get_extents(level)();  // Call a Python function
    extents_list.innerHTML = "";
    for (var i=0, n=extents.length; i<n; i++) {
        const option = new Option(extents[i]['name'], extents[i]['name']);
        extents_list.appendChild(option);
    }
    loading_extents.classList.add("hidden");
}


function get_extent(search, extents) {
    return extents.find((extent) => {
        if (extent['name'].toLowerCase().includes(search)) {
            return extent;
        }
        return false;
    });
}


async function get_products(code, level, buffer, bbox) {
    loading_products.classList.remove("hidden");
    products = await eel.get_products(code, level, buffer, bbox)();
    products.sort(function(a,b) {
        return b.code < a.code
    });
    products_tree = {root: []};
    for (var i=0, n=products.length; i<n; i++) {
        const parent = products[i]['parent'];
        if (!parent) {
            products_tree['root'].push(products[i]);
        } else {
            if (!products_tree[parent]) {
                products_tree[parent] = [];
            }
            products_tree[products[i]['parent']].push(products[i]);
        }
    }

    products_list.innerHTML = "";
    const products_root = products_tree['root'];
    if (products_root.length) {
        /*
        for (var i=0, n=products_root.length; i<n; i++) {
            var product = [];
            product.push('<div class="form-check">');
            product.push('<input class="form-check-input" type="radio" name="product" id="' + products_root[i]['code'] + '" value="' + products_root[i]['code'] + '"></input>');
            product.push('<label class="form-check-label" for="' + products_root[i]['code'] + '">');
            product.push(products_root[i]['code']);
            product.push('</label>');
            product.push('</div>');

            const subproducts = products_tree[products_root[i]['code']];
            if (subproducts && subproducts.length) {
                for (var j=0, m=subproducts.length; j<m; j++) {
                    // var product = [];
                    product.push('<div class="form-check ms-3">');
                    product.push('<input class="form-check-input" type="radio" name="product" id="' + subproducts[j]['code'] + '" value="' + subproducts[j]['code'] + '"></input>');
                    product.push('<label class="form-check-label" for="' + subproducts[j]['code'] + '">');
                    product.push(subproducts[j]['code']);
                    product.push('</label>');
                    product.push('</div>');
                }
            }

            products_list.innerHTML += product.join('\n');
        }
        */
        for (var i=0, n=products_root.length; i<n; i++) {
            var root = products_root[i];
            const children = products_tree[root['code']];
            if (children.length == 1) {
                root = children[0];
            }
            var product = [];
            product.push('<div class="form-check">');
            product.push('<input class="form-check-input" type="radio" name="product" id="' + root['code'] + '" value="' + root['code'] + '"></input>');
            product.push('<label class="form-check-label fw-bold" for="' + root['code'] + '">');
            product.push(root['name']);
            product.push('<a href="' + root['metadata_url'] + '" target="_blank" class="text-dark"><i class="bi-info-circle-fill ms-3"></i></a>');
            product.push('</label>');
            product.push('</div>');

            if (children && children.length > 1) {
                for (var j=0, m=children.length; j<m; j++) {
                    const child = children[j];
                    product.push('<div class="form-check ms-5">');
                    product.push('<input class="form-check-input" type="radio" name="product" id="' + child['code'] + '" value="' + child['code'] + '"></input>');
                    product.push('<label class="form-check-label" for="' + child['code'] + '">');
                    product.push(child['name']);
                    product.push('<a href="' + child['metadata_url'] + '" target="_blank" class="text-dark"><i class="bi-info-circle-fill ms-3"></i></a>');
                    product.push('</label>');
                    product.push('</div>');
                }
            }

            products_list.innerHTML += product.join('\n');
        }
    }
    loading_products.classList.add("hidden");
}

function get_product(product_code, products) {
    return products.find((product) => {
        if (product['code'].toLowerCase().includes(product_code)) {
            return product;
        }
        return false;
    });
}

function clear_form() {
    displayError(false);
    extents_list.innerHTML = "";
    extents_level.forEach(level => level.checked = false);
    bbox_ckeckbox.checked = false;
    tiles_list.innerHTML = '<li class="list-group-item border border-0">Empty list</li>';
    map_picture.src = './empty.png';
    nb_tiles.textContent = 0;
    extent_input.value = '';
    extent_buffer.value = 0;
    submit_btn.disabled = true;
    map_link.classList.add("hidden");
}

// On change extent level
extents_level.forEach(level => level.addEventListener('change', (e) => {
    get_extents(e.target.value);
    extent_input.value = '';
    submit_btn.disabled = true;
}));

// On type extent name
extent_input.addEventListener('change', (e) => {
    const product_checked = document.querySelector('input[name="product"]:checked');
    submit_btn.disabled = extent_input.value.length < 3 && product_checked && product_checked.value;

    const extent_name = extent_input.value.toLowerCase();
    const level_checked = document.querySelector('input[name="level"]:checked');
    const level = level_checked ? level_checked.value : false;
    // console.log(level_checked.value)
    if (extent_name && level) {
        const extent = get_extent(extent_name, extents);
        if (extent) {
            var buffer = extent_buffer.value;
            buffer = buffer ? parseInt(buffer) : 0;
            const bbox = bbox_ckeckbox.checked;
            console.log(extent_name, extent, level)
            products = get_products(extent['code'], level, buffer, bbox);
        } else {
            displayError("Il y a une erreure dans l'emprise saisie.")
        }
    } else {
        displayError("Il y a une erreure dans le formulaire. Merci de vérifier le niveau et le nom de l'emprise saisie.");
    }
});



// On submit Form
form.addEventListener('submit', (e) => {
    e.preventDefault();
    loading_submit(true);
    displayError(false);
    map_link.classList.add("hidden");

    const extent_name = extent_input.value.toLowerCase();
    const level_checked = document.querySelector('input[name="level"]:checked');
    const level = level_checked ? level_checked.value.toLowerCase() : false;
    const product_checked = document.querySelector('input[name="product"]:checked');
    const product_code = product_checked ? product_checked.value.toLowerCase() : false;
    if (extent_name && level && product_code) {
        const extent = get_extent(extent_name, extents);
        const product = get_product(product_code, products);
        if (extent) {
            var buffer = extent_buffer.value;
            buffer = buffer ? parseInt(buffer) : 0;
            const bbox = bbox_ckeckbox.checked;
            get_map(extent['code'], level, product, buffer, bbox).then(() => {
                loading_submit(false);
                map_link.classList.remove("hidden");
            });
        } else {
            displayError("Il y a une erreure dans le formulaire. Merci de vérifier l'emprise saisie.")
            loading_submit(false);
        }
    } else {
        displayError("Il y a une erreure dans le formulaire. Merci de vérifier le niveau et le nom de l'emprise saisie.")
        loading_submit(false);
    }
});

// On clear form
clear.addEventListener('click', (e) => {
    clear_form();
});

// On download_files_list
download_files_list.addEventListener('click', (e) => {
    download('files.txt', files_list.join('\n'));
});

// On download_files
download_files.addEventListener('click', (e) => {
    e.preventDefault();
    const links = document.querySelectorAll('a.file_link');
    downloadAllLinks(links);
});

// On load page
function init() {
    // A GARDER ?
    // extent_input = document.querySelector('#extent-input');
    // extent_input.onfocus = function() { extent_input.value =''; };
    clear_form();
}

init();

