const fs = require('fs');
const path = require('path');
var exec = require('child_process').exec;

const mapillaryDirectoryContainer = "/home/poule/encrypted/stockage-syncable/photos/imagerie kartaview carto tel/mapillary"; // Replace with path to source directory
const panoramaxCommand = "geovisio upload --api-url https://panoramax.openstreetmap.fr "
const reallyUploadToPanoramax = false;

/**
 * envoyer les photos d'un dossier dans panoramax
 * @param folderName
 * @returns {Promise<{name: string, email: string}>}
 */
async function importToPanoramax(folderName) {
    // Exec output contains both stderr and stdout outputs
    console.log('exec command listing ', folderName)
    const countPhotos = await exec('ls -l ' + folderName + ' |wc -l')
    console.log('countPhotos.stdout', countPhotos)
    let stdOutData = {
        name: countPhotos.stdout,

    }
    if (reallyUploadToPanoramax) {
        const uploadPanoramax = await exec(panoramaxCommand + folderName)
        stdOutData['upload'] = uploadPanoramax.stdout
    }


    return stdOutData;
}

importToPanoramax(mapillaryDirectoryContainer)
let commandOutput = [];

/**
 * lister les dossier dans un dossier et faire un upload dans panoramax
 * @param dir
 */
function traverseDirectoryTree(dir) {
    const contents = fs.readdirSync(dir);

    for (let i = 0; i < contents.length; i++) {
        let filename = contents[i];
        const fullPath = path.join(dir, filename);

        try {
            const stats = fs.lstatSync(fullPath);

            if (stats.isFile()) {
                return;
            } else if (stats.isDirectory()) {
                console.log(`Dossier ${fullPath} à envoyer`);
                // commande envoi
                // geovisio upload --api-url https://panoramax.openstreetmap.fr le_dossier_de_photos
                // traverseDirectoryTree(fullPath);

                importToPanoramax(fullPath).then(data => commandOutput.push(data))

            }
        } catch (err) {
            console.error(`Error traversing ${fullPath}: ${err}`);
        }
    }
}

traverseDirectoryTree(mapillaryDirectoryContainer);
console.log("Exiting directory tree");