'use strict'

const SpawnWatch                    = require('spawn-watch');
const starter                       = require('./engine/process-utils').starter;
const Rx                            = require('rx');
const statusEvts                    = require('./engine/configs').pmpEngineStatusEvts;
const noBrowserTabArg               = require('./engine/configs').additionalArguments.noBrowserTabArg;
const defaultIoConfig               = require('./engine/configs').defaultIoConfig;
const ioEvts                        = require('./socket-serving/ioEvts');

class PmpEngine {
    constructor(options) {
        this._status                = new Rx.BehaviorSubject(statusEvts.stopped);
        this._hellSpawn             = new SpawnWatch({ ipc:true });
        this._socketServer          = null;
        this._pimpCommandsConfig    = null;
        this._options               = {
            ioEnabled:false,
            ioServerConfig:defaultIoConfig 
        };

        //options settings (io socket serving)
        if(options) {
            this._options = Object.assign(this._options, options);
        }

        //handle socket server enabled PmpEngine
        if(this._options.ioEnabled) {

            //init socket server
            const SocketServer = require('./socket-serving/io').SocketServer;
            this._socketServer = new SocketServer(this, this._options.ioServerConfig);

            //react to external inputs (outputs are already piped)
            this._socketServer.inputStream.subscribe(socketInputActions.bind(this));
        }
    }

    //launch pmpEngine
    start(pmpConfig, additionalArgs) {
        if(!pmpConfig || !this.pmpEngineStatus === statusEvts.stopped) return false;
        this._pimpCommandsConfig = pmpConfig;
        return starter(this._hellSpawn, pmpConfig, this._status, additionalArgs);
    }

    //restart pmpEngine
    restart(pmpConfig) {
        let nextStartConfig = (pmpConfig) ? pmpConfig : Object.assign({}, this._pimpCommandsConfig);
        this.pmpEngineStatusStream
            .filter(engineStatus => { return (engineStatus === statusEvts.stopped) })
            .first()
            .subscribe(processStatus => {
                this.start(nextStartConfig, [noBrowserTabArg]);
            });
        
        return this.stop();
    }

    //stop pmpEngine
    stop() {
        return this._hellSpawn.stop();
    };

    //get pmpEngine current status
    get pmpEngineStatus() {
        return this._status.value;
    }

    get currentPimpConfig() {
        return Object.assign({}, this._pimpCommandsConfig);
    }

    /* observables */
    //status
    get pmpEngineStatusStream() {
        return this._status.asObservable().distinctUntilChanged();
    }
    //logs
    get pmpEngineLogsStream() {
        return this._hellSpawn.outEventStream;
    }
    //errors
    get pmpEngineErrorsStream() {
        return this._hellSpawn.errorStream;
    }
}

const socketInputActions = function(input) {
    switch(input.subType) {
        case 'start-command': this.start(input.payload); break;
        case 'stop-command': this.stop(); break;
        case 'restart-command': this.restart(input.payload); break;
        case 'config-command': this._socketServer.emit(ioEvts.outputs.config(this.currentPimpConfig)); break;

        default:
            console.log('pmpEngine received unknown command ' + input);
    }
}

/* ===========================================================================
  LAUNCH IN STANDALONE MODE
=========================================================================== */
process.argv.map(function(arg){
  if(arg === '--standalone'){
    console.log('PMP-ENGINE - STANDALONE MODE');

    //create pmp engine instance with socket connection
    let pmpEngine = new PmpEngine({ ioEnabled:true });
  }
});

module.exports = PmpEngine;
@@ -3674,16 +3674,65 @@
 === */%0D%0A
+let isStandAlone = false;%0D%0Alet isDebug = false;%0D%0A
 process.
@@ -3837,24 +3837,252 @@
 ODE');%0D%0A
+    isStandAlone    = true;%0D%0A    isDebug         = false;%0D%0A  %7D else if(arg === '--standalone-debug') %7B%0D%0A    console.log('PMP-ENGINE - STANDALONE MODE & DEBUG');%0D%0A    isStandAlone = isDebug = true;%0D%0A  %7D%0D%0A%7D);%0D%0A%0D%0Aif(isStandAlone) %7B
 %0D%0A    //
 create p
@@ -4073,16 +4073,17 @@
 %0D%0A    //
+ 
 create p
@@ -4181,23 +4181,289 @@
 ue %7D);%0D%0A
+%0D%0A    // debug%0D%0A    if(isDebug) %7B%0D%0A        pmpEngine._hellSpawn._status.subscribe(status =%3E %7B%0D%0A            console.log('status changes --%3E ' + status);%0D%0A            if(status === 'started') console.dir(pmpEngine._pimpCommandsConfig, %7B depth: null %7D);%0D%0A        %7D);%0D%0A  
   %7D%0D%0A%7D
-)
 ;%0D%0A%0D%0Amod

add standalone start to pmp engine