const {exec} = require("child_process");
const baseDir = "/Users/panlei/Documents/workspace/MacOCI"


function cmdExecute(command) {
    /**
     * @param {Function} resolve A function that resolves the promise
     * @param {Function} reject A function that fails the promise
     * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
     */
    return new Promise(function (resolve, reject) {
        /**
         * @param {Error} error An error triggered during the execution of the childProcess.exec command
         * @param {string|Buffer} standardOutput The result of the shell command execution
         * @param {string|Buffer} standardError The error resulting of the shell command execution
         * @see https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
         */
        exec(command, function (error, standardOutput, standardError) {
            if (error) {
                reject();

                return;
            }

            if (standardError) {
                reject(standardError);

                return;
            }

            resolve(standardOutput);
        });
    });
}

async function openUrlWithAdb(url, device) {
    // do not continue if device is blocked
    console.log("load url on device " + device.model() + " url=" + url)
    let cmd = "adb -s " + device.serial() + " shell am start -a android.intent.action.VIEW -d " + url
    try {
        let output = await cmdExecute(cmd);
        console.log(`stdout: ${output}`);
    } catch (e) {
        console.log(e)
    }
}

async function findText(imgPath) {
    // Load images
    let cmd = `${baseDir}/venv/bin/python ${baseDir}/MacOCR.py ${imgPath}`
    let stdOut = await cmdExecute(cmd);
    console.log(stdOut)
    return stdOut
}

module.exports = {findText, openUrlWithAdb}