const Devtool = require('./lib/lib/devtool');
const Config = require('./lib/lib/config');
const IP = require('ip');
const detect = require('detect-port');

const {
    logger
} = require('./lib/util/logger');

/**
 * Start server and lanunch chrome.
 * @param {Object} config 
 * - ip ip of node server.
 * - port port of node server
 * - remoteDebugPort remote-debug-port of headless.
 * - enableHeadless enable to start headless chromium or not.
 * @param {Function} cb 
 */
module.exports = (config, cb) => {
    Config.ip = (config && config.ip) ? config.ip : IP.address();
    Config.port =    (config && config.port) ? config.port : 8088;
    Config.remoteDebugPort = (config && config.remoteDebugPort) ? config.remoteDebugPort : 9222;
    Config.enableHeadless = (config && config.enableHeadless === false) ? false : true;
    Config.enableStartMessage = (config && config.enableStartMessage === true) ? true : false;

    // Check whether the port is occupied
    detect(Config.port).then( (open) => {
        Config.inUse = open !== +Config.port;
        if (Config.inUse) {
            Config.inUse = {
                old: Config.port,
                open: open
            };
            Config.port = open;
        }
        Devtool.start(null, Config, cb);
    });
}
