import { setNodes, useEditorRef } from '@udecode/plate-common';

import { TAttachmentElement } from '../base';

export type SizeLength = string | number;

export const useSizeChange = ({
  curHeight,
  curWidth,
}: {
  curWidth: SizeLength;
  curHeight: SizeLength;
}) => {
  const editor = useEditorRef();

  const setSize = ({
    width,
    height,
  }: {
    width?: SizeLength;
    height?: SizeLength;
  }) => {
    setNodes<TAttachmentElement>(editor, {
      width,
      height,
    });
  };

  const setWidth = (width: SizeLength) => {
    setNodes<TAttachmentElement>(editor, {
      width,
    });
  };

  const setHeight = (height: SizeLength) => {
    const numberHeight = getMatchNumberValue(height);
    const numberCurWidth = getMatchNumberValue(curWidth);
    const numberCurHeight = getMatchNumberValue(curHeight);
    if (numberHeight < 0 || numberCurWidth < 0 || numberCurHeight < 0) return;
    const _width = Math.ceil(numberCurWidth * (numberHeight / numberCurHeight));
    setSize({ width: _width, height });
  };
  return {
    setWidth,
    setHeight,
  };
};

export function getMatchNumberValue(value?: string | number) {
  const valueMatch = value?.toString().match(/\d+/);
  if (!valueMatch) return 0;
  const numberValue = Number.parseInt(valueMatch[0], 10);
  return numberValue;
}
