// @flow
import '../../common/RichTextEditorInlineReply.js';
import _ from '../../../util/i18n';
const isMac = process.platform === 'darwin';
let anchor = '';

function fireEvent(event) {
  // Use console.log to notify wrapping container that change has occurred
  console.log(event);
}

const stripInternalUrl = (url) => {
  if (url.includes('richtexteditor.html#')) {
    return url.split('richtexteditor.html')[1];
  }
  return url;
};

const clearPopups = () => {
  [...document.getElementsByClassName('tooltip-text')].forEach(el => {
    el && el.parentElement && el.parentElement.classList.remove('tooltip');
    el.remove();
  });
};

const selectTextAndExec = (command: string, event: MouseEvent) => {
  const selection = window.getSelection();
  selection.setBaseAndExtent(
    selection.focusNode, 0, selection.focusNode, selection.focusNode.length
  );
  fireEvent(command);
  event.preventDefault();
  event.stopPropagation();
};

const onKeyDown = (event: KeyboardEvent) => {
  const key = event.key.toLowerCase();
  if (event.altKey && event.shiftKey && key === 's') {
    document.execCommand('strikeThrough', false, null);
  } else if (isMac ? event.metaKey : event.ctrlKey) {
    switch (key) {
      case 'k':
        fireEvent('createLink');
        event.preventDefault();
        event.stopPropagation();
        break;
      case 's':
        // Prevent browser save dialog
        event.preventDefault();
        event.stopPropagation();
        break;
      default:
        break;
    }
  }
};

const preventDefault = (event: MouseEvent) => {
  event.preventDefault();
};

const renderLinkToolbar = (event: MouseEvent) => {
  clearPopups();
  // $FlowFixMe select all anchor text first to remove existing link
  const clickedLink = event.target.closest('a');
  if (!clickedLink) {
    return;
  }

  const tooltip = document.createElement('SPAN');
  tooltip.classList.add('tooltip-text');
  tooltip.setAttribute('contenteditable', 'false');

  const tooltipLink = document.createElement('A');
  const href= stripInternalUrl(clickedLink.href);
  tooltipLink.setAttribute('href', href);
  if (!href.startsWith('#')) {
    tooltipLink.setAttribute('target', '_blank');
  }
  tooltipLink.appendChild(document.createTextNode(href));

  const tooltipCopyButton = document.createElement('INPUT');
  tooltipCopyButton.setAttribute('type', 'button');
  tooltipCopyButton.setAttribute('value', _('link', 'Copy'));
  tooltipCopyButton.setAttribute('title', _('Copy Link Address'));

  const tooltipEditButton = document.createElement('INPUT');
  tooltipEditButton.setAttribute('type', 'button');
  tooltipEditButton.setAttribute('value', _('link', 'Edit'));
  tooltipCopyButton.setAttribute('title', _('Edit Link Address'));

  const tooltipUnlinkButton = document.createElement('INPUT');
  tooltipUnlinkButton.setAttribute('type', 'button');
  tooltipUnlinkButton.setAttribute('value', _('link', 'Remove'));
  tooltipUnlinkButton.setAttribute('title', _('Remove Link'));

  tooltip.appendChild(tooltipLink);
  tooltip.appendChild(tooltipCopyButton);
  tooltip.appendChild(tooltipEditButton);
  tooltip.appendChild(tooltipUnlinkButton);
  clickedLink.classList.add('tooltip');
  clickedLink.appendChild(tooltip);

  tooltipCopyButton.addEventListener('mousedown', preventDefault);
  tooltipCopyButton.addEventListener('click', (event: MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    clearPopups();
    navigator.clipboard.writeText(anchor);
    fireEvent(`copyLink ${anchor}`);
  });
  tooltipEditButton.addEventListener('mousedown', preventDefault);
  tooltipEditButton.addEventListener('click', (event: MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    clearPopups();
    selectTextAndExec('editLink', event);
  });
  tooltipUnlinkButton.addEventListener('mousedown', preventDefault);
  tooltipUnlinkButton.addEventListener('click', (event: MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    clearPopups();
    selectTextAndExec('unlink', event);
  });
};

const getAnchor = () => {
  const sel = document.getSelection();
  if (sel && sel.focusNode && sel.focusNode.parentElement) {
    const anchorElement: ?Element = sel.focusNode.parentElement.closest('a');
    if (anchorElement instanceof HTMLAnchorElement && anchorElement.href) {
      return stripInternalUrl(anchorElement.href);
    }
  }
  return '';
};

const onSelectionChange = (event: Event) => {
  const currentAnchor = getAnchor();
  if (anchor !== currentAnchor) {
    anchor = currentAnchor;
    fireEvent(`linkupdate ${currentAnchor}`);
  } else if (!currentAnchor) {
    anchor = '';
    fireEvent('linkupdate');
  }
  fireEvent('selectionchange');
};

function init() {
  document.body && document.body.focus();
  document.addEventListener('input', () => fireEvent('input'));
  document.addEventListener('selectionchange', onSelectionChange);
  document.addEventListener('keydown', onKeyDown);
  document.addEventListener('click', renderLinkToolbar);
  window.addEventListener('blur', clearPopups);
}

init();
