var m = require('mithril');
var moderationView = require('./moderation').view;
var presetView = require('./preset').view;

var delocalizePattern = /(^|[\s\n]|<[A-Za-z]*\/?>)\w{2}\.lichess\.org/gi;

function delocalize(html) {
  return html.replace(delocalizePattern, '$1lichess.org');
}

function escapeHtml(html) {
  return html
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

var linkPattern = /(^|[\s\n]|<[A-Za-z]*\/?>)((?:(?:https?):\/\/|lichess\.org\/)[\-A-Z0-9+\u0026\u2019@#\/%?=()~_|!:,.;]*[\-A-Z0-9+\u0026@#\/%=~()_|])/gi;

function autoLink(html) {
  return html.replace(linkPattern, '$1<a target="_blank" rel="nofollow" href="$2">$2</a>');
};

var deletedEm = '<em class="deleted">&lt;deleted&gt;</em>';

function renderLine(ctrl) {
  return function(line) {
    if (!line.html) line.html = m.trust(autoLink(escapeHtml(delocalize(line.t))));
    if (line.u === 'lichess') return m('li.system', line.t);
    if (line.c) return m('li', [
      m('span', '[' + line.c + ']'),
      line.t
    ]);
    return m('li', {
      'data-username': line.u
    }, [
      ctrl.vm.isMod ? moderationView.lineAction() : null,
      m.trust(
        $.userLinkLimit(line.u, 14) + (line.d ? deletedEm : line.html)
      )
    ]);
  };
}

function sameLines(l1, l2) {
  return l1.d && l2.d && l1.u === l2.u;
}

function selectLines(ctrl) {
  var prev, ls = [];
  ctrl.data.lines.forEach(function(l) {
    if (!prev || !sameLines(prev, l))
      if (!l.r || ctrl.vm.isTroll) ls.push(l);
    prev = l;
  });
  return ls;
}

function input(ctrl) {
  if (ctrl.data.loginRequired && !ctrl.data.userId) return m('input.lichess_say', {
    placeholder: 'Login to chat',
    disabled: true
  });
  var placeholder;
  if (ctrl.vm.isTimeout()) placeholder = 'You have been timed out.';
  else if (!ctrl.vm.writeable()) placeholder = 'Invited members only.';
  else placeholder = ctrl.trans(ctrl.vm.placeholderKey);
  return m('input', {
    class: 'lichess_say',
    placeholder: placeholder,
    autocomplete: 'off',
    maxlength: 140,
    disabled: ctrl.vm.isTimeout() || !ctrl.vm.writeable(),
    config: function(el, isUpdate) {
      if (!isUpdate) el.addEventListener('keypress', function(e) {
        if (e.which == 10 || e.which == 13) {
          ctrl.post(e.target.value);
          e.target.value = '';
        }
      });
    }
  })
}

module.exports = {
  view: function(ctrl) {
    if (!ctrl.vm.enabled()) return null;
    return [
      m('ol.messages.content.scroll-shadow-soft', {
          config: function(el, isUpdate, ctx) {
            if (!isUpdate && ctrl.moderation) $(el).on('click', 'i.mod', function(e) {
              ctrl.moderation.open($(e.target).parent().data('username'));
            });
            if (ctrl.data.lines.length > 5) {
              var autoScroll = (el.scrollTop === 0 || (el.scrollTop > (el.scrollHeight - el.clientHeight - 100)));
              el.scrollTop = 999999;
              if (autoScroll) setTimeout(function() {
                el.scrollTop = 999999;
              }, 500);
            }
          }
        },
        selectLines(ctrl).map(renderLine(ctrl))
      ),
      input(ctrl),
      presetView(ctrl.preset)
    ];
  }
};

@@ -626,123 +626,357 @@
 i;%0A%0A
-function autoLink(html) %7B%0A  return html.replace(linkPattern, '$1%3Ca target=%22_blank%22 rel=%22nofollow%22 href=%22$2%22%3E$2%3C/a%3E'
+var linkReplace = function(match, before, url) %7B%0A  var fullUrl = url.indexOf('http') === 0 ? url : 'https://' + url;%0A  var minUrl = url.replace(/%5E(?:https:%5C/%5C/)?(.+)$/, '$1');%0A  return before + '%3Ca target=%22_blank%22 rel=%22nofollow%22 href=%22' + fullUrl + '%22%3E' + minUrl + '%3C/a%3E';%0A%7D;%0A%0Afunction autoLink(html) %7B%0A  return html.replace(linkPattern, linkReplace
 );%0A%7D
@@ -1233,17 +1233,20 @@
 ', line.
-t
+html
 );%0A    i

improve chat autolinks