(function() {
  var EE, Promise, Windows, _, menu, savedState;

  _ = require("lodash");

  EE = require("events");

  Promise = require("bluebird");

  menu = require("../gui/menu");

  Windows = require("../gui/windows");

  savedState = require("../saved_state");

  module.exports = {
    _defaultOptions: function(state, options) {
      var _this;
      _this = this;
      return _.defaults({}, options, {
        x: state.browserX,
        y: state.browserY,
        width: state.browserWidth || 1280,
        height: state.browserHeight || 720,
        devTools: state.isBrowserDevToolsOpen,
        minWidth: 100,
        minHeight: 100,
        contextMenu: true,
        trackState: {
          width: "browserWidth",
          height: "browserHeight",
          x: "browserX",
          y: "browserY",
          devTools: "isBrowserDevToolsOpen"
        },
        onFocus: function() {
          return menu.set({
            withDevTools: true
          });
        },
        onNewWindow: function(e, url) {
          var _win;
          _win = this;
          return _this._launchChild(e, url, _win, state, options).then(function(child) {
            return _win.on("close", function() {
              if (!child.isDestroyed()) {
                return child.close();
              }
            });
          });
        }
      });
    },
    _render: function(url, state, options) {
      var win;
      if (options == null) {
        options = {};
      }
      options = this._defaultOptions(state, options);
      win = Windows.create(options);
      return this._launch(win, url, options);
    },
    _launchChild: function(e, url, parent, state, options) {
      var parentX, parentY, ref, win;
      e.preventDefault();
      ref = parent.getPosition(), parentX = ref[0], parentY = ref[1];
      options = this._defaultOptions(state, options);
      _.extend(options, {
        x: parentX + 100,
        y: parentY + 100,
        trackState: false,
        onPaint: null
      });
      win = Windows.create(options);
      e.newGuest = win;
      return this._launch(win, url, options);
    },
    _launch: function(win, url, options) {
      menu.set({
        withDevTools: true
      });
      return Promise["try"]((function(_this) {
        return function() {
          var ps;
          if (ps = options.proxyServer) {
            return _this._setProxy(win.webContents, ps);
          }
        };
      })(this)).then(function() {
        return win.loadURL(url);
      })["return"](win);
    },
    _setProxy: function(webContents, proxyServer) {
      return new Promise(function(resolve) {
        return webContents.session.setProxy({
          proxyRules: proxyServer
        }, resolve);
      });
    },
    open: function(browserName, url, options, automation) {
      if (options == null) {
        options = {};
      }
      return savedState(options.projectPath).then(function(state) {
        return state.get();
      }).then((function(_this) {
        return function(state) {
          return _this._render(url, state, options).then(function(win) {
            var a, call, events, invoke;
            a = Windows.automation(win);
            invoke = function(method, data) {
              return a[method](data);
            };
            automation.use({
              onRequest: function(message, data) {
                switch (message) {
                  case "get:cookies":
                    return invoke("getCookies", data);
                  case "get:cookie":
                    return invoke("getCookie", data);
                  case "set:cookie":
                    return invoke("setCookie", data);
                  case "clear:cookies":
                    return invoke("clearCookies", data);
                  case "clear:cookie":
                    return invoke("clearCookie", data);
                  case "is:automation:client:connected":
                    return invoke("isAutomationConnected", data);
                  case "take:screenshot":
                    return invoke("takeScreenshot");
                  default:
                    throw new Error("No automation handler registered for: '" + message + "'");
                }
              }
            });
            call = function(method) {
              return function() {
                if (!win.isDestroyed()) {
                  return win[method]();
                }
              };
            };
            events = new EE;
            win.once("closed", function() {
              call("removeAllListeners");
              return events.emit("exit");
            });
            return _.extend(events, {
              browserWindow: win,
              kill: call("close"),
              removeAllListeners: call("removeAllListeners")
            });
          });
        };
      })(this));
    }
  };

}).call(this);
