var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.defaultEmojiSearchIndex = exports.ProgressIndicatorTypes = exports.MessageStatusTypes = exports.FileState = void 0;
exports.escapeRegExp = escapeRegExp;
exports.stringifyMessage = exports.reduceMessagesToString = exports.makeImageCompatibleUrl = exports.isLocalUrl = exports.isEditedMessage = exports.isBouncedMessage = exports.isBlockedMessage = exports.hasOnlyEmojis = exports.getUrlWithoutParams = exports.getIndicatorTypeForFileState = exports.getFileTypeFromMimeType = exports.getFileNameFromPath = exports.getDurationLabelFromDuration = exports.generateRandomId = exports.findInMessagesById = exports.findInMessagesByDate = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _dayjs = _interopRequireDefault(require("dayjs"));
var _emojiRegex = _interopRequireDefault(require("emoji-regex"));
var _emojiData = require("../emoji-data");
var _types = require("../types/types");
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
var FileState = exports.FileState = Object.freeze({
  FINISHED: 'finished',
  NOT_SUPPORTED: 'not_supported',
  UPLOAD_FAILED: 'upload_failed',
  UPLOADED: 'uploaded',
  UPLOADING: 'uploading'
});
var ProgressIndicatorTypes = exports.ProgressIndicatorTypes = Object.freeze({
  IN_PROGRESS: 'in_progress',
  INACTIVE: 'inactive',
  NOT_SUPPORTED: 'not_supported',
  RETRY: 'retry'
});
var MessageStatusTypes = exports.MessageStatusTypes = {
  FAILED: 'failed',
  RECEIVED: 'received',
  SENDING: 'sending'
};
var getIndicatorTypeForFileState = exports.getIndicatorTypeForFileState = function getIndicatorTypeForFileState(fileState, enableOfflineSupport) {
  var indicatorMap = (0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])((0, _defineProperty2["default"])({}, FileState.UPLOADING, enableOfflineSupport ? ProgressIndicatorTypes.INACTIVE : ProgressIndicatorTypes.IN_PROGRESS), FileState.UPLOAD_FAILED, enableOfflineSupport ? ProgressIndicatorTypes.INACTIVE : ProgressIndicatorTypes.RETRY), FileState.NOT_SUPPORTED, ProgressIndicatorTypes.NOT_SUPPORTED), FileState.UPLOADED, ProgressIndicatorTypes.INACTIVE), FileState.FINISHED, ProgressIndicatorTypes.INACTIVE);
  return indicatorMap[fileState];
};
var isBlockedMessage = exports.isBlockedMessage = function isBlockedMessage(message) {
  var pattern = /\bMessage was blocked by moderation policies\b/;
  return message.type === 'error' && message.text && pattern.test(message.text);
};
var isBouncedMessage = exports.isBouncedMessage = function isBouncedMessage(message) {
  var _message$moderation_d, _message$moderation;
  return message.type === 'error' && (message == null || (_message$moderation_d = message.moderation_details) == null ? void 0 : _message$moderation_d.action) === 'MESSAGE_RESPONSE_ACTION_BOUNCE' || (message == null || (_message$moderation = message.moderation) == null ? void 0 : _message$moderation.action) === 'bounce';
};
var isEditedMessage = exports.isEditedMessage = function isEditedMessage(message) {
  return !!message.message_text_updated_at;
};
var defaultEmojiSearchIndex = exports.defaultEmojiSearchIndex = {
  search: function search(query) {
    try {
      var results = [];
      var _loop = function _loop(emoji) {
          if (results.length >= 10) {
            return {
              v: results
            };
          }
          if (emoji.names.some(function (name) {
            return name.includes(query);
          })) {
            if (emoji.skins) {
              results.push(Object.assign({}, emoji, {
                name: "".concat(emoji.name, "-tone-1"),
                skins: undefined
              }));
              emoji.skins.forEach(function (tone, index) {
                return results.push(Object.assign({}, emoji, {
                  name: "".concat(emoji.name, "-tone-").concat(index + 2),
                  skins: undefined,
                  unicode: tone
                }));
              });
            } else {
              results.push(emoji);
            }
          }
        },
        _ret;
      var _iterator = _createForOfIteratorHelper(_emojiData.compiledEmojis),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var emoji = _step.value;
          _ret = _loop(emoji);
          if (_ret) return _ret.v;
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      return results;
    } catch (error) {
      console.warn('Error searching emojis:', error);
      throw error;
    }
  }
};
var makeImageCompatibleUrl = exports.makeImageCompatibleUrl = function makeImageCompatibleUrl(url) {
  return (url.indexOf('//') === 0 ? "https:".concat(url) : url).trim();
};
var getUrlWithoutParams = exports.getUrlWithoutParams = function getUrlWithoutParams(url) {
  if (!url) {
    return url;
  }
  var indexOfQuestion = url.indexOf('?');
  if (indexOfQuestion === -1) {
    return url;
  }
  return url.substring(0, url.indexOf('?'));
};
var isLocalUrl = exports.isLocalUrl = function isLocalUrl(url) {
  return url.indexOf('http') !== 0;
};
var _generateRandomId = exports.generateRandomId = function generateRandomId() {
  var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return a ? ((Number(a) ^ Math.random() * 16) >> Number(a) / 4).toString(16) : "".concat(1e7, "-", 1e3, "-", 4e3, "-", 8e3, "-", 1e11).replace(/[018]/g, _generateRandomId);
};
var hasOnlyEmojis = exports.hasOnlyEmojis = function hasOnlyEmojis(text) {
  try {
    var emojiOnlyString = (0, _toConsumableArray2["default"])(text.matchAll((0, _emojiRegex["default"])())).join('');
    var originalTextWithNoSpaces = text.replaceAll(/\s/g, '');
    return emojiOnlyString.length !== 0 && emojiOnlyString.length === originalTextWithNoSpaces.length;
  } catch (e) {
    return false;
  }
};
var stringifyMessage = exports.stringifyMessage = function stringifyMessage(message) {
  var deleted_at = message.deleted_at,
    i18n = message.i18n,
    latest_reactions = message.latest_reactions,
    reaction_groups = message.reaction_groups,
    reply_count = message.reply_count,
    status = message.status,
    text = message.text,
    type = message.type,
    updated_at = message.updated_at;
  return "".concat(latest_reactions ? latest_reactions.map(function (_ref) {
    var type = _ref.type,
      user = _ref.user;
    return "".concat(type).concat(user == null ? void 0 : user.id);
  }).join() : '').concat(reaction_groups ? Object.entries(reaction_groups).flatMap(function (_ref2) {
    var _ref3 = (0, _slicedToArray2["default"])(_ref2, 2),
      type = _ref3[0],
      _ref3$ = _ref3[1],
      count = _ref3$.count,
      first_reaction_at = _ref3$.first_reaction_at,
      last_reaction_at = _ref3$.last_reaction_at;
    return "".concat(type).concat(count).concat(first_reaction_at).concat(last_reaction_at);
  }).join() : '').concat(type).concat(deleted_at).concat(text).concat(reply_count).concat(status).concat(updated_at).concat(JSON.stringify(i18n));
};
var reduceMessagesToString = exports.reduceMessagesToString = function reduceMessagesToString(messages) {
  return messages.map(stringifyMessage).join();
};
var getFileNameFromPath = exports.getFileNameFromPath = function getFileNameFromPath(path) {
  var pattern = /[^/]+\.[^/]+$/;
  var match = path.match(pattern);
  return match ? match[0] : '';
};
var getFileTypeFromMimeType = exports.getFileTypeFromMimeType = function getFileTypeFromMimeType(mimeType) {
  var fileType = mimeType.split('/')[0];
  if (fileType === 'image') {
    return _types.FileTypes.Image;
  } else if (fileType === 'video') {
    return _types.FileTypes.Video;
  } else if (fileType === 'audio') {
    return _types.FileTypes.Audio;
  }
  return _types.FileTypes.File;
};
var getDurationLabelFromDuration = exports.getDurationLabelFromDuration = function getDurationLabelFromDuration(duration) {
  if (!duration) {
    return '00:00';
  }
  var ONE_HOUR_IN_SECONDS = 3600;
  var ONE_HOUR_IN_MILLISECONDS = ONE_HOUR_IN_SECONDS * 1000;
  var durationLabel = '00:00';
  var isDurationLongerThanHour = duration / ONE_HOUR_IN_MILLISECONDS >= 1;
  var formattedDurationParam = isDurationLongerThanHour ? 'HH:mm:ss' : 'mm:ss';
  var formattedVideoDuration = _dayjs["default"].duration(duration, 'milliseconds').format(formattedDurationParam);
  durationLabel = formattedVideoDuration;
  return durationLabel;
};
function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,/\\^$|#]/g, '\\$&');
}
var findInMessagesById = exports.findInMessagesById = function findInMessagesById(messages, targetId) {
  var idx = messages.findIndex(function (message) {
    return message.id === targetId;
  });
  return idx;
};
var findInMessagesByDate = exports.findInMessagesByDate = function findInMessagesByDate(messages, targetDate) {
  var targetTimestamp = targetDate.getTime();
  var left = 0;
  var right = messages.length - 1;
  var middle = 0;
  while (left <= right) {
    var _messages, _messages2;
    middle = Math.floor(left + (right - left) / 2);
    var middleTimestamp = new Date(messages[middle].created_at).getTime();
    var middleLeftTimestamp = ((_messages = messages[middle - 1]) == null ? void 0 : _messages.created_at) && new Date(messages[middle - 1].created_at).getTime();
    var middleRightTimestamp = ((_messages2 = messages[middle + 1]) == null ? void 0 : _messages2.created_at) && new Date(messages[middle + 1].created_at).getTime();
    if (middleTimestamp === targetTimestamp || middleLeftTimestamp && middleRightTimestamp && middleLeftTimestamp < targetTimestamp && middleRightTimestamp > targetTimestamp) {
      return {
        index: middle,
        message: messages[middle]
      };
    } else if (middleTimestamp < targetTimestamp) {
      left = middle + 1;
    } else {
      right = middle - 1;
    }
  }
  return {
    index: -1
  };
};
//# sourceMappingURL=utils.js.map