'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.embedEmojis = exports.fetchEmojis = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /* eslint-disable no-cond-assign */


var _emojiRegex = require('emoji-regex');

var _emojiRegex2 = _interopRequireDefault(_emojiRegex);

var _textLayout = require('@react-pdf/text-layout');

var _font = require('../font');

var _font2 = _interopRequireDefault(_font);

var _image = require('../utils/image');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// Caches emoji images data
var emojis = {};
var regex = (0, _emojiRegex2.default)();

var reflect = function reflect(promise) {
  return function () {
    return promise.apply(undefined, arguments).then(function (v) {
      return v;
    }, function (e) {
      return e;
    });
  };
};

var fetchEmojiImage = reflect(_image.fetchImage);

var getCodePoints = function getCodePoints(string) {
  return Array.from(string).map(function (char) {
    return char.codePointAt(0).toString(16);
  }).join('-');
};

var buildEmojiUrl = function buildEmojiUrl(emoji) {
  var _Font$getEmojiSource = _font2.default.getEmojiSource(),
      url = _Font$getEmojiSource.url,
      format = _Font$getEmojiSource.format;

  return '' + url + getCodePoints(emoji) + '.' + format;
};

var fetchEmojis = exports.fetchEmojis = function fetchEmojis(string) {
  var emojiSource = _font2.default.getEmojiSource();

  if (!emojiSource || !emojiSource.url) {
    console.warn('Emoji source not registered');
    return [];
  }

  var promises = [];

  var match = void 0;

  var _loop = function _loop() {
    var emoji = match[0];

    if (!emojis[emoji] || emojis[emoji].loading) {
      var emojiUrl = buildEmojiUrl(emoji);

      emojis[emoji] = { loading: true };

      promises.push(fetchEmojiImage(emojiUrl).then(function (image) {
        emojis[emoji].loading = false;
        emojis[emoji].data = image.data;
      }));
    }
  };

  while (match = regex.exec(string)) {
    _loop();
  }

  return promises;
};

var embedEmojis = exports.embedEmojis = function embedEmojis(fragments) {
  var result = [];

  for (var i = 0; i < fragments.length; i++) {
    var fragment = fragments[i];

    var match = void 0;
    var lastIndex = 0;

    while (match = regex.exec(fragment.string)) {
      var index = match.index;
      var _emoji = match[0];
      var emojiSize = fragment.attributes.fontSize;
      var chunk = fragment.string.slice(lastIndex, index + match[0].length);

      // If emoji image was found, we create a new fragment with the
      // correct attachment and object substitution character;
      if (emojis[_emoji] && emojis[_emoji].data) {
        result.push({
          string: chunk.replace(match, _textLayout.Attachment.CHARACTER),
          attributes: _extends({}, fragment.attributes, {
            attachment: new _textLayout.Attachment(emojiSize, emojiSize, {
              yOffset: Math.floor(emojiSize * 0.1),
              image: emojis[_emoji].data
            })
          })
        });
      } else {
        // If no emoji data, we just replace the emoji with a nodef char
        result.push({
          string: chunk.replace(match, String.fromCharCode(0)),
          attributes: fragment.attributes
        });
      }

      lastIndex = index + _emoji.length;
    }

    if (lastIndex < fragment.string.length) {
      result.push({
        string: fragment.string.slice(lastIndex),
        attributes: fragment.attributes
      });
    }
  }

  return result;
};