function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/**
 * @file Transforms BUIE FeedItems into @box/activity-feed component props.
 *
 * Read data comes from the file activities endpoint (already parsed into BUIE FeedItem types).
 * Write/mutate operations still use the traditional v2 API via ActivitySidebar callbacks.
 * @author Box
 */

import { TaskCompletionRule, TaskType } from '@box/activity-feed';
import { AnnotationBadgeType } from '@box/threaded-annotations';
import { convertMillisecondsToTimestamp } from '../../../utils/timestamp';
import { FEED_ITEM_TYPE_ANNOTATION, FEED_ITEM_TYPE_APP_ACTIVITY, FEED_ITEM_TYPE_COMMENT, FEED_ITEM_TYPE_TASK, FEED_ITEM_TYPE_VERSION } from '../../../constants';
const MENTION_REGEX = /@\[(\d+):([^\]]+)\]/g;
const parseLine = (line, authorId) => {
  const nodes = [];
  let lastIndex = 0;
  MENTION_REGEX.lastIndex = 0;
  let match = MENTION_REGEX.exec(line);
  while (match !== null) {
    const [fullMatch, userId, userName] = match;
    const {
      index
    } = match;
    if (index > lastIndex) {
      nodes.push({
        type: 'text',
        text: line.slice(lastIndex, index)
      });
    }
    nodes.push({
      type: 'mention',
      attrs: {
        authorId,
        mentionId: userId,
        mentionedUserId: userId,
        mentionedUserName: userName
      }
    });
    lastIndex = index + fullMatch.length;
    match = MENTION_REGEX.exec(line);
  }
  if (lastIndex < line.length) {
    nodes.push({
      type: 'text',
      text: line.slice(lastIndex)
    });
  }
  return nodes;
};
export const textToDocumentNode = (text, authorId) => {
  if (!text) {
    return {
      type: 'doc',
      content: []
    };
  }
  const lines = text.split('\n');
  const content = lines.map(line => {
    const nodes = parseLine(line, authorId);
    return _objectSpread({
      type: 'paragraph'
    }, nodes.length > 0 ? {
      content: nodes
    } : {});
  });
  return {
    type: 'doc',
    content
  };
};
const toUnixMs = isoDate => {
  if (!isoDate) return undefined;
  const ms = new Date(isoDate).getTime();
  return Number.isNaN(ms) ? undefined : ms;
};
const toUpdatedAt = (createdAt, modifiedAt) => {
  if (modifiedAt === createdAt) return undefined;
  return toUnixMs(modifiedAt);
};
const toUserAuthor = user => ({
  avatarUrl: user?.avatar_url,
  email: user?.email ?? user?.login ?? '',
  id: Number(user?.id) || 0,
  name: user?.name ?? ''
});
const toPermissions = permissions => ({
  canDelete: permissions?.can_delete ?? false,
  canEdit: permissions?.can_edit ?? false,
  canReply: permissions?.can_reply ?? false,
  canResolve: permissions?.can_resolve ?? false
});
const commentToTextMessage = comment => ({
  author: toUserAuthor(comment.created_by),
  createdAt: toUnixMs(comment.created_at) ?? 0,
  id: comment.id,
  message: textToDocumentNode(comment.tagged_message || comment.message || '', comment.created_by?.id ?? ''),
  permissions: toPermissions(comment.permissions),
  updatedAt: toUpdatedAt(comment.created_at, comment.modified_at)
});
export const transformCommentToMessages = comment => {
  const root = commentToTextMessage(comment);
  const replies = (comment.replies ?? []).map(reply => commentToTextMessage(reply));
  return [root, ...replies];
};
export const annotationTargetToBadge = target => {
  if (!target) return undefined;
  if (target.location?.type === 'frame') {
    return {
      timestamp: convertMillisecondsToTimestamp(target.location.value ?? 0),
      type: AnnotationBadgeType.Frame
    };
  }
  const page = target.location?.value ?? 0;
  switch (target.type) {
    case 'drawing':
      return {
        page,
        type: AnnotationBadgeType.Drawing
      };
    case 'highlight':
      return {
        highlightedText: target.text ?? '',
        page,
        type: AnnotationBadgeType.Highlight
      };
    case 'point':
      return {
        page,
        type: AnnotationBadgeType.Point
      };
    case 'region':
      return {
        page,
        type: AnnotationBadgeType.Region
      };
    default:
      return undefined;
  }
};
export const transformAnnotationToMessages = annotation => {
  const messageText = annotation.description?.message ?? '';
  const root = {
    author: toUserAuthor(annotation.created_by),
    createdAt: toUnixMs(annotation.created_at) ?? 0,
    id: annotation.id,
    message: textToDocumentNode(messageText, annotation.created_by?.id ?? ''),
    permissions: toPermissions(annotation.permissions),
    updatedAt: toUpdatedAt(annotation.created_at, annotation.modified_at)
  };
  const replies = (annotation.replies ?? []).map(reply => commentToTextMessage(reply));
  return [root, ...replies];
};
export const transformTaskToProps = (task, currentUserId) => ({
  assignees: (task.assigned_to?.entries ?? []).map(entry => ({
    avatarUrl: entry.target?.avatar_url,
    completedAt: toUnixMs(entry.completed_at),
    id: entry.target?.id ?? entry.id,
    name: entry.target?.name ?? '',
    permissions: entry.permissions ? {
      canDelete: entry.permissions.can_delete,
      canUpdate: entry.permissions.can_update
    } : undefined,
    status: entry.status
  })),
  author: {
    avatarUrl: task.created_by?.target?.avatar_url,
    id: task.created_by?.target?.id ?? '',
    name: task.created_by?.target?.name ?? ''
  },
  completedAt: toUnixMs(task.completed_at),
  completionRule: task.completion_rule === 'ALL_ASSIGNEES' ? TaskCompletionRule.ALL_ASSIGNEES : TaskCompletionRule.ANY_ASSIGNEE,
  createdAt: toUnixMs(task.created_at) ?? 0,
  currentUserId,
  description: task.description,
  dueDate: toUnixMs(task.due_at),
  hasNextPage: Boolean(task.assigned_to?.next_marker),
  id: task.id,
  permissions: {
    canCreateTaskCollaborator: task.permissions?.can_create_task_collaborator ?? false,
    canCreateTaskLink: task.permissions?.can_create_task_link ?? false,
    canDelete: task.permissions?.can_delete ?? false,
    canUpdate: task.permissions?.can_update ?? false
  },
  status: task.status,
  taskType: task.task_type === 'APPROVAL' ? TaskType.APPROVAL : TaskType.GENERAL
});
const mapActionTypeString = actionType => {
  switch (actionType) {
    case 'delete':
    case 'trashed':
      return 'delete';
    case 'promote':
    case 'promoted':
      return 'promote';
    case 'restore':
    case 'restored':
      return 'restore';
    case 'upload':
    case 'created':
      return 'upload';
    default:
      return undefined;
  }
};
const getVersionAction = version => {
  if (version.version_promoted) return 'promote';
  if (version.restored_at) return 'restore';
  if (version.trashed_at) return 'delete';
  return mapActionTypeString(version.action_type) ?? 'upload';
};
const getVersionUser = version => version.restored_by || version.trashed_by || version.promoted_by || version.modified_by || undefined;
export const transformVersionToProps = version => {
  const user = getVersionUser(version);
  return {
    actionType: getVersionAction(version),
    authorName: user?.name ?? version.uploader_display_name,
    avatarUrl: user?.avatar_url,
    createdAt: toUnixMs(version.created_at),
    id: version.id,
    versionNumber: parseInt(version.version_number, 10) || version.version_end || 0
  };
};
export const transformAppActivityToProps = item => ({
  appIconUrl: item.app?.icon_url ?? '',
  appName: item.app?.name ?? '',
  createdAt: toUnixMs(item.created_at) ?? 0,
  id: item.id,
  renderedText: item.rendered_text ?? ''
});
export const transformFeedItem = (item, currentUserId) => {
  switch (item.type) {
    case FEED_ITEM_TYPE_COMMENT:
      {
        const comment = item;
        const commentIsResolved = comment.status === 'resolved';
        return {
          id: comment.id,
          isResolved: commentIsResolved,
          messages: transformCommentToMessages(comment),
          originalText: comment.tagged_message || comment.message || '',
          permissions: comment.permissions ?? {},
          resolvedAt: commentIsResolved ? toUnixMs(comment.resolution?.resolved_at) : undefined,
          resolvedBy: commentIsResolved ? comment.resolution?.resolved_by?.name : undefined,
          status: comment.status,
          type: 'comment'
        };
      }
    case FEED_ITEM_TYPE_ANNOTATION:
      {
        const annotation = item;
        const annotationIsResolved = annotation.status === 'resolved';
        return {
          annotation,
          id: annotation.id,
          isResolved: annotationIsResolved,
          messages: transformAnnotationToMessages(annotation),
          permissions: annotation.permissions ?? {},
          resolvedAt: annotationIsResolved ? toUnixMs(annotation.resolution?.resolved_at) : undefined,
          resolvedBy: annotationIsResolved ? annotation.resolution?.resolved_by?.name : undefined,
          status: annotation.status,
          type: 'annotation'
        };
      }
    case FEED_ITEM_TYPE_TASK:
      {
        const task = item;
        return {
          id: item.id,
          originalTask: task,
          props: transformTaskToProps(task, currentUserId),
          type: 'task'
        };
      }
    case FEED_ITEM_TYPE_VERSION:
      return {
        id: item.id,
        props: transformVersionToProps(item),
        type: 'version'
      };
    case FEED_ITEM_TYPE_APP_ACTIVITY:
      return {
        id: item.id,
        props: transformAppActivityToProps(item),
        type: 'app_activity'
      };
    default:
      return null;
  }
};
//# sourceMappingURL=transformers.js.map