(function() {
  var linkAtPosition, linkForName, linkUnderCursor, openLink, selector, shell, url, _;

  url = require('url');

  shell = require('shell');

  _ = require('underscore-plus');

  selector = null;

  module.exports = {
    activate: function() {
      return atom.commands.add('atom-workspace', 'link:open', openLink);
    }
  };

  openLink = function() {
    var editor, link, protocol;
    editor = atom.workspace.getActiveTextEditor();
    if (editor == null) {
      return;
    }
    link = linkUnderCursor(editor);
    if (link == null) {
      return;
    }
    if (editor.getGrammar().scopeName === 'source.gfm') {
      link = linkForName(editor.getBuffer(), link);
    }
    protocol = url.parse(link).protocol;
    if (protocol === 'http:' || protocol === 'https:') {
      return shell.openExternal(link);
    }
  };

  linkUnderCursor = function(editor) {
    var cursorPosition, link;
    cursorPosition = editor.getCursorBufferPosition();
    link = linkAtPosition(editor, cursorPosition);
    if (link != null) {
      return link;
    }
    if (cursorPosition.column > 0) {
      return linkAtPosition(editor, cursorPosition.translate([0, -1]));
    }
  };

  linkAtPosition = function(editor, bufferPosition) {
    var ScopeSelector, token;
    if (selector == null) {
      ScopeSelector = require('first-mate').ScopeSelector;
      selector = new ScopeSelector('markup.underline.link');
    }
    if (token = editor.tokenForBufferPosition(bufferPosition)) {
      if (token.value && selector.matches(token.scopes)) {
        return token.value;
      }
    }
  };

  linkForName = function(buffer, linkName) {
    var link, regex;
    link = linkName;
    regex = new RegExp("^\\s*\\[" + (_.escapeRegExp(linkName)) + "\\]\\s*:\\s*(.+)$", 'g');
    buffer.backwardsScanInRange(regex, buffer.getRange(), function(_arg) {
      var match, stop;
      match = _arg.match, stop = _arg.stop;
      link = match[1];
      return stop();
    });
    return link;
  };

}).call(this);
