#!/usr/bin/env node
/*
 * Copyright 2017 Red Hat Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var webdriverio = require('webdriverio');
var selenium = require('selenium-standalone');
var optionsParser = require('../client-lib/optionsParser.js');

var args = require('yargs')
    .usage('$0 [args]')
    .options({
        'client-type':  { default: 'sender', describe: 'type of client', type: 'string', choices: ['sender', 'receiver', 'connector']},
    })
    .help('help')
    .argv;

var options;
if(args['client-type'] === 'sender') {
    options = new optionsParser.SenderOptions();
}else if(args['client-type'] === 'receiver') {
    options = new optionsParser.ReceiverOptions();
}else if(args['client-type'] === 'connector') {
    options = new optionsParser.ConnectorOptions();
}
options.ParseArguments(process.argv.slice(4));

/**
 * @class BrowserTestsRunner
 * @description Class represents executor for browser base client using selenium
 */
var BrowserTestsRunner = function() {};

BrowserTestsRunner.prototype.constructor = BrowserTestsRunner;

/**
* @function PrintResults
* @static
* @description print output of html page to console output
* @param {object} res - object for print
* @memberof BrowserTestsRunner
*/
BrowserTestsRunner.PrintResults = function(res) {
    if(typeof res === 'string') {
        console.log(res);
    }else{
        res.forEach(function(elem) {
            console.log(elem);
        });
    }
};

/**
* @function Run
* @public
* @description Run client browser executor
* @memberof BrowserTestsRunner
*/
BrowserTestsRunner.prototype.Run = function() {
    var timeout = 3000;

    selenium.start({}, function(err, cp) {
        if (err) {
            console.log(err);
            return;
        }

        var htmlPath = __dirname + '/client.html';
        var seleniumOpts = {
            desiredCapabilities: {
                browserName: 'chrome',
                chromeOptions: {
                    args: ['--headless'],
                }
            }
        };
        var driver = webdriverio.remote(seleniumOpts);

        driver.on('error', function(e) {
            console.log(e.body.value.class);
            console.log(e.body.value.message);
        });

        driver
            .init()
            .url('file://' + htmlPath)
            .execute(function(clientType ,args) {
                var client = require("cli-rhea");
                var cli = client.SenderClient;
                if(clientType === 'receiver') {
                    cli = client.ReceiverClient;
                }else if (clientType === 'connector') {
                    cli = client.ConnectorClient;
                }
                cli.Run(args);
            }, args['client-type'], options)
            .pause(timeout)
            .getText('div').then(BrowserTestsRunner.PrintResults)
            .call(
                function() {
                    setTimeout(function(cp) {
                        cp.kill();
                    }, 500, cp);
                }
            )
            .end();
    });
};
///////////////////////////////////////////////////////////////////////////////////
/**
 * @module BrowserTestsRunner
 * @description BrowserTestsRunner class
 */

/** BrowserTestsRunner class */
exports.BrowserTestsRunner = BrowserTestsRunner;

@@ -776,16 +776,111 @@
 er.js');
+%0Avar Utils = require('../client-lib/utils.js');%0Avar driver = null;%0Avar seleniumProccess = null;
 %0A%0Avar ar
@@ -2069,16 +2069,549 @@
   %7D%0A%7D;%0A%0A
+/**%0A* @function RunnerScript%0A* @static%0A* @description script for run client in browser%0A* @param %7Bstring%7D clientType - type of client%0A* @param %7Bstring%7D args - arguments for client%0A* @memberof BrowserTestsRunner%0A*/%0ABrowserTestsRunner.RunnerScript = function(clientType ,args) %7B%0A    var client = require(%22cli-rhea%22);%0A    var cli = client.SenderClient;%0A    if(clientType === 'receiver') %7B%0A        cli = client.ReceiverClient;%0A    %7Delse if (clientType === 'connector') %7B%0A        cli = client.ConnectorClient;%0A    %7D%0A    cli.Run(args);%0A%7D;%0A%0A
 /**%0A* @f
@@ -2821,24 +2821,55 @@
 (err, cp) %7B%0A
+        seleniumProccess = cp;%0A
         if (
@@ -3216,20 +3216,16 @@
         
-var 
 driver =
@@ -3317,64 +3317,36 @@
     
-console.log(e.body.value.class);%0A            console.log
+throw new Utils.ErrorHandler
 (e.b
@@ -3477,399 +3477,39 @@
 ute(
-function(clientType ,args) %7B%0A                var client = require(%22cli-rhea%22);%0A                var cli = client.SenderClient;%0A                if(clientType === 'receiver') %7B%0A                    cli = client.ReceiverClient;%0A                %7Delse if (clientType === 'connector') %7B%0A                    cli = client.ConnectorClient;%0A                %7D%0A                cli.Run(args);%0A            %7D
+BrowserTestsRunner.RunnerScript
 , ar
@@ -3854,16 +3854,155 @@
   %7D);%0A%7D;
+%0A%0Aprocess.on('uncaughtException', function(err) %7B%0A    driver.end();%0A    seleniumProccess.kill();%0A    throw new Utils.ErrorHandler(err);%0A%7D);
 %0A///////

add error handler for browser runner