/**
* @flow
* This file is generated automatically, run npm run build to re-generate.
**/

import type { Options } from './flow-types/options';
import type Driver from './driver';
import { resolve } from 'url';
import addDebugging from './add-debugging';
import BaseClass from './base-class';

/*
 * Navigation object
 *
 * @deprecated These methods all now live directly on the "ActiveWindow" object.
 */
class Navigator extends BaseClass {
  _options: Options;

  constructor(driver: Driver, options: Options) {
    super(driver);
    this._options = options;
  }

  /*
   * Navigate forwards in the browser history, if possible.
   */
  forward(): void {
    this.requestJSON('POST', '/forward');
  }

  /*
   * Navigate backwards in the browser history, if possible.
   */
  backward(): void {
    this.requestJSON('POST', '/back');
  }

  /*
   * Refreshes the browser
   */
  refresh(): void {
    this.requestJSON('POST', '/refresh');
  }

  /*
   * Get the current url that the browser is displaying
   */
  getUrl(): string {
    return this.requestJSON('GET', '/url');
  }

  /*
   * Navigates the browser to the specified path
   *
   *  - if `path` begins with a "/" it is relative to `options.base`
   *  - if `path` begins with "http" it is absolute
   *  - otherwise it is relative to the current path
   */
  navigateTo(path: string): void {
    if (path[0] === '/') {
      const base = this._options.base;
      if (!base) {
        throw new Error('You must provide a "base" option to use urls starting with "/"');
      }
      path = base.replace(/\/$/, '') + path;
    } else if (path.indexOf('http') !== 0) {
      const base = this.getUrl();
      this.navigateTo(resolve(base, path));
      return;
    }

    this.driver.requestJSON('POST', '/url', { url: path });
  }
}

/*
 * Navigates the browser to the specified path
 *
 * Alias for `navigateTo`
 *
 * @method setUrl
 * @param {String} path
 */
(Navigator.prototype: any).setUrl = Navigator.prototype.navigateTo;
addDebugging(Navigator);
export default Navigator;