import lodash from "lodash";
import {
  ButtonData_Type,
  HTMLData_Source,
  PluginContainerData_Alignment,
  PluginContainerData_Width_Type
} from "./../../../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import {
  ACTION_BUTTON_TYPE,
  APP_EMBED_TYPE,
  AUDIO_TYPE,
  COLLAPSIBLE_LIST_TYPE,
  DIVIDER_TYPE,
  EMBED_TYPE,
  EXTERNAL,
  FILE_UPLOAD_TYPE,
  GALLERY_TYPE,
  GIPHY_TYPE,
  HTML_TYPE,
  IMAGE_TYPE,
  IMAGE_TYPE_LEGACY,
  LINK_BUTTON_TYPE,
  LINK_PREVIEW_TYPE,
  LINK_TYPE,
  MENTION_TYPE,
  NO_WRAP,
  POLL_TYPE,
  TABLE_TYPE,
  VIDEO_TYPE,
  VIDEO_TYPE_LEGACY,
  WRAP
} from "../../../consts.js";
import { toSizeInKb } from "../../../file-size-utils/to-size-in-kb.js";
import { createLink } from "../../node-utils.js";
import { roundNumericValue } from "../utils.js";
import { TO_RICOS_DATA } from "./consts.js";
import { convertJsonToStruct } from "./convert-json-to-struct.js";
const toConstantCase = (str) => lodash.snakeCase(str).toUpperCase();
const supportedContainerDataAlignments = [
  PluginContainerData_Alignment.CENTER,
  PluginContainerData_Alignment.LEFT,
  PluginContainerData_Alignment.RIGHT
];
const convertBlockDataToRicos = (type, data) => {
  const newData = lodash.cloneDeep(data);
  const converters = {
    [VIDEO_TYPE]: convertVideoData,
    [VIDEO_TYPE_LEGACY]: convertLegacyVideoData,
    [AUDIO_TYPE]: convertAudioData,
    [DIVIDER_TYPE]: convertDividerData,
    [FILE_UPLOAD_TYPE]: convertFileData,
    [GIPHY_TYPE]: convertGIFData,
    [IMAGE_TYPE]: convertImageData,
    [IMAGE_TYPE_LEGACY]: convertImageData,
    [POLL_TYPE]: convertPollData,
    [APP_EMBED_TYPE]: convertAppEmbedData,
    [LINK_PREVIEW_TYPE]: convertLinkPreviewData,
    [MENTION_TYPE]: convertMentionData,
    [LINK_BUTTON_TYPE]: convertButtonData,
    [ACTION_BUTTON_TYPE]: convertButtonData,
    [COLLAPSIBLE_LIST_TYPE]: convertCollapsibleListData,
    [HTML_TYPE]: convertHTMLData,
    [EMBED_TYPE]: convertEmbedData,
    [LINK_TYPE]: convertLinkData,
    [TABLE_TYPE]: convertTableData,
    [GALLERY_TYPE]: convertGalleryData,
    [EXTERNAL]: convertExternalData
  };
  let blockType = type;
  if (type === LINK_PREVIEW_TYPE && data.html) {
    blockType = EMBED_TYPE;
  }
  if ([IMAGE_TYPE_LEGACY, IMAGE_TYPE].includes(type) && !newData.config) {
    newData.config = {};
  }
  if (newData.config && blockType !== EXTERNAL) {
    convertContainerData(newData, blockType);
  }
  if (blockType in converters) {
    const convert = converters[blockType];
    convert(newData, blockType);
  }
  const fromJSON = (data2) => {
    const pluginDataMethods = TO_RICOS_DATA[blockType];
    return pluginDataMethods?.fromJSON(data2) || data2;
  };
  return fromJSON(newData);
};
const convertContainerData = (data, blockType) => {
  const { size, alignment, width, spoiler, height, textWrap = WRAP } = data.config || {};
  const { enabled, description, buttonContent } = spoiler || {};
  const newSpoiler = spoiler && {
    enabled: enabled || false,
    description,
    buttonText: buttonContent
  };
  const normalizedAlignment = alignment?.toUpperCase();
  data.containerData = {
    alignment: normalizedAlignment && supportedContainerDataAlignments.includes(
      normalizedAlignment
    ) ? normalizedAlignment : null,
    spoiler: newSpoiler,
    textWrap: textWrap !== NO_WRAP
  };
  typeof height === "number" && (data.containerData.height = { custom: parseInt(height.toString(), 10) });
  if (typeof width === "number" && (blockType !== IMAGE_TYPE || !size || size === "inline")) {
    data.containerData.width = { custom: parseInt(width.toString(), 10) };
  } else if (size) {
    const validSize = PluginContainerData_Width_Type[toConstantCase(size)];
    data.containerData.width = { size: validSize ?? PluginContainerData_Width_Type.CONTENT };
  }
  if (blockType === ACTION_BUTTON_TYPE || blockType === LINK_BUTTON_TYPE) {
    if (width === "fit-content") {
      data.containerData.width = { size: "ORIGINAL" };
    }
  }
  if (blockType === IMAGE_TYPE && data.containerData.width?.size === "ORIGINAL" && data.src?.width && lodash.isNumber(data.src.width) && data.src.width > 350) {
    data.containerData.alignment = data.containerData.alignment || "CENTER";
  }
};
const convertVideoData = (data) => {
  if (typeof data.src === "string" && data.src) {
    data.video = { src: { url: data.src } };
    const {
      oembed,
      thumbnail_url,
      width: thumbnail_width,
      height: thumbnail_height,
      title
    } = data.metadata || {};
    let src, width, height;
    if (oembed) {
      const { thumbnail_url: thumbnail_url2, thumbnail_width: thumbnail_width2, thumbnail_height: thumbnail_height2 } = oembed;
      src = thumbnail_url2 ? { url: thumbnail_url2 } : void 0;
      width = thumbnail_width2;
      height = thumbnail_height2;
    } else {
      src = thumbnail_url ? { url: thumbnail_url } : void 0;
      width = thumbnail_width;
      height = thumbnail_height;
    }
    const titleResolved = oembed ? oembed.title : title;
    titleResolved && (data.title = titleResolved);
    data.thumbnail = src || width || height ? { src, width, height } : void 0;
  } else if (typeof data.src === "object" && data.src.pathname) {
    data.video = { src: { id: data.src.pathname } };
    data.thumbnail = data.src.thumbnail ? {
      src: { id: data.src.thumbnail.pathname },
      width: data.src.thumbnail.width,
      height: data.src.thumbnail.height
    } : void 0;
  }
  data.video && (data.video.duration = data.duration);
};
const convertLegacyVideoData = (data) => {
  const { url, oembed, src } = data;
  if (url ?? src) {
    data.video = { src: { url: url ?? src } };
  }
  delete data.url;
  if (oembed) {
    const { thumbnail_url, thumbnail_width, thumbnail_height, title } = oembed;
    if (thumbnail_url) {
      data.thumbnail = {
        src: { url: thumbnail_url },
        width: thumbnail_width ? Number(thumbnail_width) : void 0,
        height: thumbnail_height ? Number(thumbnail_height) : void 0
      };
    }
    if (title) {
      data.title = oembed.title;
    }
    delete data.oembed;
  }
  data.containerData = {
    alignment: PluginContainerData_Alignment.CENTER,
    textWrap: true
  };
};
const convertAudioData = (data) => {
  const { coverImage } = data;
  if (coverImage) {
    const { file_name, width, height } = coverImage;
    data.coverImage = { file_name, src: { id: file_name }, width, height };
  }
};
const convertGalleryStyles = (styles) => {
  styles.layout = {};
  styles.item = {};
  styles.thumbnails = {};
  lodash.has(styles, "galleryLayout") && (styles.layout.type = styles.galleryLayout);
  lodash.has(styles, "oneRow") && (styles.layout.horizontalScroll = styles.oneRow);
  lodash.has(styles, "isVertical") && (styles.layout.orientation = styles.isVertical ? "COLUMNS" : "ROWS");
  lodash.has(styles, "m_numberOfImagesPerRow") && (styles.layout.mobileNumberOfColumns = styles.m_numberOfImagesPerRow);
  if (lodash.has(styles, "m_numberOfImagesPerRow") && !isNaN(parseInt(styles.m_numberOfImagesPerRow, 10))) {
    styles.layout.mobileNumberOfColumns = styles.m_numberOfImagesPerRow;
  }
  if (lodash.has(styles, "gallerySizePx") && !isNaN(parseInt(styles.gallerySizePx, 10))) {
    styles.item.targetSize = styles.gallerySizePx;
  }
  if (lodash.has(styles, "numberOfImagesPerRow") && !isNaN(parseInt(styles.numberOfImagesPerRow, 10))) {
    styles.layout.numberOfColumns = styles.numberOfImagesPerRow;
  }
  if (lodash.has(styles, "cubeRatio")) {
    if (typeof styles.cubeRatio === "string") {
      const [x, y] = styles.cubeRatio.split("/");
      if (!(Number.isNaN(parseInt(x, 10)) && Number.isNaN(parseInt(y, 10)))) {
        styles.item.ratio = Math.trunc(parseInt(x, 10) / parseInt(y, 10) * 100) / 100;
      }
    } else {
      styles.item.ratio = styles.cubeRatio;
    }
  }
  const cubeType = styles?.cubeType?.toUpperCase();
  ["FIT", "FILL"].includes(cubeType) && (styles.item.crop = cubeType);
  if (lodash.has(styles, "imageMargin") && !isNaN(parseInt(styles.imageMargin, 10))) {
    styles.item.spacing = styles.imageMargin;
  }
  const thumbnailPlacement = styles?.galleryThumbnailsAlignment?.toUpperCase();
  styles.thumbnails.placement = ["TOP", "BOTTOM", "LEFT", "RIGHT"].includes(thumbnailPlacement) ? thumbnailPlacement : "NONE";
  if (lodash.has(styles, "thumbnailSpacings") && !isNaN(parseInt(styles.thumbnailSpacings, 10))) {
    styles.thumbnails.spacing = Math.trunc(styles.thumbnailSpacings);
  }
  return styles;
};
const convertGalleryItem = (item) => {
  const {
    url,
    metadata: { type = "image", poster, height, width, link, title, altText }
  } = item;
  item[type] = { media: { src: { url }, height, width } };
  title && (item.title = title);
  altText && (item.altText = altText);
  if (type === "video" && poster) {
    const src = { url: poster.url || poster };
    item.video.thumbnail = { src, height: poster.height || height, width: poster.width || width };
  }
  type === "image" && link && (item.image.link = createLink(link));
  return item;
};
const convertGalleryData = (data) => {
  lodash.has(data, "items") && (data.items = data.items.map((item) => convertGalleryItem(item)));
  lodash.has(data, "styles") && (data.options = convertGalleryStyles(data.styles));
};
const convertDividerData = (data) => {
  lodash.has(data, "type") && (data.lineStyle = data.type?.toUpperCase());
  lodash.has(data, "config.size") && (data.width = data.config?.size?.toUpperCase());
  lodash.has(data, "config.alignment") && (data.alignment = data.config?.alignment?.toUpperCase());
  data.containerData.width = { size: PluginContainerData_Width_Type.CONTENT };
};
const convertExternalData = (data) => {
  data.fields = convertJsonToStruct(data).fields;
};
const convertImageData = (data) => {
  if (isNaN(parseInt(data.width))) {
    delete data.width;
  }
  if (isNaN(parseInt(data.height))) {
    delete data.height;
  }
  if (typeof data.src === "string") {
    data.image = {
      src: { source: "static", url: data.src },
      width: ensureValidNumber(data.width),
      height: ensureValidNumber(data.height)
    };
  } else if (typeof data.src === "object" && data.src !== null) {
    if ("url" in data.src && typeof data.src.url === "string") {
      const { url, width, height } = data.src || {};
      data.image = {
        src: { url },
        width: ensureValidNumber(width),
        height: ensureValidNumber(height)
      };
    } else if ("file_name" in data.src && typeof data.src.file_name === "string" && data.src.file_name) {
      const { file_name, width, height } = data.src || {};
      data.image = {
        src: { id: file_name },
        width: ensureValidNumber(width),
        height: ensureValidNumber(height)
      };
    }
  }
  const { link, anchor } = data.config || {};
  data.link = (link || anchor) && createLink({ ...link, anchor });
  data.altText = data.metadata?.alt;
  data.caption = data.metadata?.caption;
};
const convertGIFData = (data) => {
  const { gif } = data;
  const {
    originalUrl,
    originalMp4,
    stillUrl,
    downsizedUrl,
    downsizedSmallMp4,
    downsizedStillUrl,
    height,
    width
  } = gif || {};
  data.original = { gif: originalUrl, mp4: originalMp4, still: stillUrl };
  data.downsized = { gif: downsizedUrl, mp4: downsizedSmallMp4, still: downsizedStillUrl };
  data.height = height;
  data.width = width;
  delete data.gif;
};
const convertPollData = (data) => {
  lodash.has(data, "layout.poll.type") && (data.layout.poll.type = data.layout.poll.type.toUpperCase());
  lodash.has(data, "layout.poll.direction") && (data.layout.poll.direction = data.layout.poll.direction.toUpperCase());
  if (lodash.has(data, "layout.option")) {
    data.layout.options = data.layout.option;
    delete data.layout.option;
  }
  if (lodash.has(data, "design")) {
    const { poll = {}, option = {} } = data.design;
    const { backgroundType, background } = poll;
    const regex = /(\d*)px/;
    const getBackground = (background2) => background2?.angle ? {
      gradient: {
        angle: background2.angle,
        startColor: background2?.start?.toUpperCase(),
        lastColor: background2.end?.toUpperCase()
      }
    } : background2?.charAt?.(0) === "#" ? { color: background2?.toUpperCase() } : { image: { src: { url: background2 } } };
    data.design = {
      poll: {
        background: {
          type: backgroundType?.toUpperCase(),
          ...getBackground(background)
        },
        borderRadius: parseInt(regex.exec(poll.borderRadius)?.[1] || "0")
      },
      options: { borderRadius: parseInt(regex.exec(option.borderRadius)?.[1] || "0") }
    };
  }
  lodash.has(data, "poll.id") && (data.poll.pollId = data.poll.id);
  lodash.has(data, "poll.createdBy") && (data.poll.creatorId = data.poll.createdBy);
  lodash.has(data, "poll.mediaId") && (data.poll.image = { src: { url: data.poll.mediaId } });
  lodash.has(data, "poll.options") && (data.poll.options = data.poll.options.map(({ mediaId, ...rest }) => ({
    image: { src: { url: mediaId } },
    ...rest
  })));
  if (lodash.has(data, "poll.settings")) {
    const { multipleVotes, voteRole, resultsVisibility, votersDisplay, votesDisplay } = data.poll.settings;
    const getViewRole = (resultsVisibility2) => resultsVisibility2 === "ALWAYS" ? "EVERYONE" : resultsVisibility2 === "VOTERS_ONLY" ? "VOTERS" : "CREATOR";
    data.poll.settings = {
      permissions: {
        view: getViewRole(resultsVisibility),
        vote: voteRole,
        allowMultipleVotes: multipleVotes
      },
      showVoters: votersDisplay,
      showVotesCount: votesDisplay
    };
  }
  lodash.has(data, "containerData.width.size") && (data.containerData.width.size = "CONTENT");
};
const convertAppEmbedData = (data) => {
  const {
    id,
    name,
    imageSrc,
    imageHeight,
    imageWidth,
    description,
    pageUrl,
    scheduling,
    location,
    html,
    durations
  } = data.selectedProduct;
  data.url = pageUrl || html && (data.url = html.match(/href="[^"]*/g)?.[0]?.slice(6));
  data.itemId = id;
  data.name = name;
  data.image = { src: { url: imageSrc }, width: imageWidth, height: imageHeight };
  if (data.type === "booking") {
    data.bookingData = { durations: durations || description };
  } else if (data.type === "event") {
    data.eventData = {
      location: location || description && description.match(/[^|]*$/)?.[0],
      scheduling: scheduling || description && description.match(/[^|]+/)?.[0]
    };
  }
  data.type = data.type?.toUpperCase();
};
const convertLinkPreviewData = (data) => {
  lodash.has(data, "thumbnail_url") && (data.thumbnailUrl = data.thumbnail_url);
  data.config?.link && (data.link = createLink(data.config?.link));
};
const convertMentionData = (data) => {
  data.name = data.mention?.name;
  data.slug = data.mention?.slug;
  data.id = data.mention?.id;
  delete data.mention;
};
const convertFileData = (data) => {
  const { url, id, privacy, size } = data;
  const isPrivate = typeof privacy !== "undefined" ? privacy === "private" : void 0;
  const src = { url, id, private: isPrivate };
  data.src = src;
  if (size) {
    data.sizeInKb = toSizeInKb(size);
    const FILE_MAX_SIZE_IN_BYTES = 2e9;
    data.size = Math.min(size, FILE_MAX_SIZE_IN_BYTES);
  }
};
const convertCollapsibleListData = (data) => {
  const { config } = data || {};
  const { expandState, expandOnlyOne, direction, isQapageData } = config || {};
  const getInitialExpandedItems = (expandState2) => {
    if (expandState2 === "expanded") {
      return "ALL";
    }
    if (expandState2 === "collapsed") {
      return "NONE";
    }
    return "FIRST";
  };
  data.initialExpandedItems = getInitialExpandedItems(expandState);
  data.expandOnlyOne = expandOnlyOne;
  data.isQapageData = isQapageData;
  data.direction = direction?.toUpperCase();
};
const convertButtonData = (data, blockType) => {
  const { settings, design } = data.button || {};
  const { borderRadius, borderWidth, background, backgroundColor, color, borderColor } = design || {};
  const { buttonText, url, rel, target } = settings || {};
  data.styles = {
    colors: { text: color, border: borderColor, background: background || backgroundColor },
    border: {
      radius: roundNumericValue(borderRadius),
      width: roundNumericValue(borderWidth)
    }
  };
  data.type = blockType === ACTION_BUTTON_TYPE ? ButtonData_Type.ACTION : ButtonData_Type.LINK;
  data.text = buttonText;
  if (data.type === ButtonData_Type.LINK && url) {
    data.link = createLink({
      url,
      rel,
      target
    });
  }
};
const convertHTMLData = (data) => {
  const { src, srcType, config } = data;
  if (config?.isAdsense) {
    data.source = HTMLData_Source.ADSENSE;
  }
  data[srcType] = src;
};
const convertEmbedData = (data) => {
  const url = data.config?.link?.url;
  url && (data.src = url);
  data.oembed = {
    type: "rich",
    thumbnailUrl: data.thumbnail_url,
    title: data.title,
    description: data.description,
    html: data.html
  };
};
const convertLinkData = (data) => {
  data.link = createLink(data);
};
const convertTableData = (data) => {
  const {
    config: { colsWidth, rowsHeight, colsMinWidth, rowHeader, colHeader }
  } = data;
  const colsWidthRatio = colsWidth.map((width) => parseInt(width, 10));
  data.dimensions = { colsWidthRatio, rowsHeight, colsMinWidth };
  data.rowHeader = rowHeader;
  data.columnHeader = colHeader;
};
const ensureValidNumber = (value) => {
  if (!value) {
    return value;
  }
  const stringValue = value?.toString();
  if (stringValue.endsWith("%")) {
    return 1e3;
  }
  const numberValue = parseInt(value?.toString(), 10);
  if (isNaN(numberValue)) {
    return void 0;
  }
  return numberValue;
};
export {
  convertBlockDataToRicos
};
//# sourceMappingURL=convert-ricos-plugin-data.js.map
