import { AttachmentAttrs } from "../schema";
import { Box, box } from "./box";

export interface Attachment {
  hidePreview: boolean;
  id: string;
  name?: string;
  naturalSize?: Box;
  type?: string;
}

/**
 * Translates attributes of a ProseMirror "at" node into a more friendly
 * interface that handles default values and uses human-friendly properties.
 */
export function decode(attrs: AttachmentAttrs): Attachment {
  return {
    ...(attrs.fn !== undefined ? { name: attrs.fn } : null),
    // Assume `hidePreview` is false when not defined.
    hidePreview: attrs.hp === true,
    id: attrs.id,
    // We can't guarantee `iw` and `ih` are both defined, so take care to decode.
    ...(attrs.nw !== undefined && attrs.nh !== undefined ? { naturalSize: box(attrs.nw, attrs.nh) } : null),
    ...(attrs.t !== undefined ? { type: attrs.t } : null)
  };
}
