const request = require('request-promise');

class BrowserstackService {
  before(capabilities) {
    this.sessionId = global.browser.sessionId;
    this.auth = global.browser.requestHandler.auth || {};
    this.failures = 0;

    return request({
      uri: `https://www.browserstack.com/automate/sessions/${this.sessionId}.json`,
      json: true,
      auth: this.auth
    }, function(error, response, body) {
      if (!error && response.statusCode === 200) {
        const { device, browserName, os, os_version, browser, browser_version } = capabilities;
        const browserString = device ? `${device} ${browserName}` : `${os} ${os_version} ${browser} ${browser_version}`;
        console.log(`[Browserstack] ${browserString} session: ${body.automation_session.browser_url}`);
      }
    });
  }

  afterSuite (suite) {
    if (suite.hasOwnProperty('err')) {
      this.failures++;
    }
  }

  afterTest (test) {
    if (!test.passed) {
      this.failures++;
    }
  }

  after() {
    return this._update(this.sessionId, this._getBody());
  }

  onReload(oldSessionId, newSessionId) {
    this.sessionId = newSessionId;
    return this._update(this.sessionId, this._getBody());
  }

  _update(sessionId, body) {
    return request({
      method: 'PUT',
      uri: `https://www.browserstack.com/automate/sessions/${sessionId}.json`,
      json: true,
      auth: this.auth,
      body
    });
  }

  _getBody() {
    return {
      status: (this.failures === 0) ? 'completed' : 'error'
    };
  }
}

module.exports = BrowserstackService;

@@ -469,41 +469,122 @@
     
-const %7B 
+// These keys describe the browser the test was run on%0A        const browserDesc = %5B'
 device
+'
 , 
-browserName
+'os'
 , 
+'
 os
+Version'
 , 
+'
 os_v
@@ -593,172 +593,268 @@
 sion
+'
 , 
+'
 browser
+Name'
 , 
+'
 browser
-_version %7D = capabilities;%0A        const browserString = device ? %60$%7Bdevice%7D $%7BbrowserName%7D%60 : %60$%7Bos%7D $%7Bos_version%7D $%7Bbrowser%7D $%7Bbrowser_version%7D%60
+', 'browserVersion', 'browser_version'%5D;%0A        const browserString = browserDesc.reduce((res, k) =%3E %7B%0A          if (capabilities%5Bk%5D) %7B%0A            res.push(capabilities%5Bk%5D);%0A          %7D%0A          return res;%0A        %7D, %5B%5D).join(' ')
 ;%0A  

Fix logging of capabilities