let spawn = require('child_process').spawn;
let rootPath = process.cwd();
let path=require('path');
let fs = require('fs-extra');
let apptoRun=path.join(rootPath, 'nodeplayer');
let updatePath = path.join(rootPath, 'update');
async function runApp() {
    await  updateApp();

    if (!await fs.pathExists(apptoRun)) {
        console.log(`watchdog could not locate ${apptoRun}, exiting..`);
        process.exit(9);
    }
    console.log(`spawning ${apptoRun}`);
    const child = spawn( apptoRun);

    console.log(`Spawned child pid: ${child.pid}`);

    child.stdin.end();

    child.stdout.on('data',async (data) => {
        console.log("" + data);
        //Here is where the output goes
    });
    child.stderr.on('data',async (data) => {
        console.log('stderr: ' + data);
        //Here is where the error output goes
    });
    child.on('close', async (code) => {
        console.log('closing code: ' + code);
        //Here you can get the exit code of the script

        await runApp()
    });
    child.on('error',async (err)=>{
        console.log('error:' + err);
        process.exit(8)
    })

}


async function updateApp() {
    try {
        console.log('checking updates');

        if (await fs.pathExists(updatePath)) {
            let files = await fs.readdir(updatePath);
            for (let i=0;i<files.length;i++){
                console.log(`moving file/folder ${files[i]} to ${rootPath}`);
                await fs.move( path.join(updatePath,files[i]),path.join(rootPath,files[i]),{overwrite:true})
            }
            console.log(`removing update folder ${updatePath}`);
            await fs.remove(updatePath);
            console.log('update completed')
        }else{
            console.log('there is no update..')
        }
    }
    catch(ex){
        console.log('error on move:' + JSON.stringify( ex))
    }

}

async function Main() {

    let args=process.argv;
    if(args.length==3){
        apptoRun=args[2];
    }
    if(args.length==4){
        updatePath=args[3];
    }
    if (args.length <= 4) {
        console.log('usage watchdog <pathOfExe> [<pathOfUpdatePath>]')
    }
    await runApp();
}

function isCompiled() {
    return ((typeof process.pkg) == 'object');
}

Main();

setInterval(() => {

}, 2000);