import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useState } from 'react';
import { IconExternalLinkSmallOutline } from '@teamleader/ui-icons';
import Box from '../../box';
import Link from '../../link';
import theme from './theme.css';

var findLinkEntities = function findLinkEntities(contentBlock, callback, contentState) {
  contentBlock.findEntityRanges(function (character) {
    var entityKey = character.getEntity();
    return entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK';
  }, callback);
};

var LinkEntity = function LinkEntity(_ref) {
  var entityKey = _ref.entityKey,
      contentState = _ref.contentState,
      children = _ref.children;

  var _useState = useState(),
      _useState2 = _slicedToArray(_useState, 2),
      showOpenLinkIcon = _useState2[0],
      setShowOpenLinkIcon = _useState2[1];

  var _contentState$getEnti = contentState.getEntity(entityKey).getData(),
      url = _contentState$getEnti.url;

  var openLink = function openLink() {
    var prefixedUrl = url;

    if (!url.includes('//')) {
      prefixedUrl = '//' + url;
    }

    window.open(prefixedUrl, '_blank');
  };

  var toggleShowOpenLinkIcon = function toggleShowOpenLinkIcon() {
    setShowOpenLinkIcon(!showOpenLinkIcon);
  };

  return /*#__PURE__*/React.createElement(Box, {
    display: "inline-block",
    onMouseEnter: toggleShowOpenLinkIcon,
    onMouseLeave: toggleShowOpenLinkIcon
  }, /*#__PURE__*/React.createElement(Link, {
    className: theme['link'],
    inherit: false,
    onClick: function onClick(event) {
      return event.preventDefault();
    }
  }, children), showOpenLinkIcon && /*#__PURE__*/React.createElement(IconExternalLinkSmallOutline, {
    onClick: openLink,
    className: theme['icon']
  }));
};

export default {
  strategy: findLinkEntities,
  component: LinkEntity
};