import { fabric } from "fabric";
import {
  clearObjects,
  sortObjects,
  transformHighlightedText,
  checkTextBoxHeight,
} from "../../components/canvas/utils";
import { PaddedHighlightingTextbox } from "../../components/canvas/textbox";

let mainTextBox = null;
let mainTextBoxBackground = null;

let personNameText = null;
let personInfoSeparator = null;
let personPositionText = null;

let mainImage = null;
let logoImage = null;

let contractedByTextbox = null;

let arrow = null;

let mainImageSource = null;
let previousLogoPosition = null;

const redraw = async (canvas, options) => {
  clearObjects(
    [
      mainTextBox,
      mainTextBoxBackground,
      personNameText,
      personInfoSeparator,
      personPositionText,
      contractedByTextbox,
      arrow,
    ],
    canvas,
  );

  canvas.preserveObjectStacking = true;

  const textMarginLeft = Math.ceil(canvas.width * 0.14);
  const textMarginRight = Math.ceil(canvas.width * 0.075);

  let mainTextMarginBottom = Math.ceil(canvas.height * 0.06);
  const mainTextBackgroundMarginTop = Math.ceil(canvas.height * 0.14);
  const mainTextSize = Math.ceil(canvas.height * 0.0725);
  const mainTextHeightLimit = Math.ceil(mainTextSize * 3.3);
  const mainTextLineHeight = 1;

  const bottomTextSize = Math.ceil(canvas.height * 0.03);
  const nameTextMarginTop = Math.ceil(canvas.height * 0.015);
  const nameTextExtraBottomMargin = Math.ceil(canvas.height * 0.06);
  const positionTextSideGap = Math.ceil(canvas.width * 0.01);
  const positionTextSeparatorWidth = Math.ceil(canvas.width * 0.0035);
  const positionTextMaxWidth = Math.ceil(canvas.width * 0.4);

  const contractedByTextSize = Math.ceil(canvas.height * 0.02);
  const contractedByTextMaxWidth = Math.ceil(canvas.width * 0.9);
  const contractedByTextSidesMargin = Math.ceil(canvas.width * 0.03);

  const arrowWidth = Math.ceil(canvas.width * 0.047);
  const arrowHeight = Math.ceil(canvas.width * 0.055);
  const arrowThickness = Math.ceil(canvas.width * 0.019);
  const arrowMarginLeft = Math.ceil(canvas.width * 0.08);
  const arrowMarginLeftExtra = Math.ceil(canvas.width * -0.01);
  const arrowMarginTop = Math.ceil(canvas.height * 0.011);

  const logoWidth = Math.ceil(canvas.width * 0.2);
  const logoSideMargin = Math.ceil(canvas.width * 0.07);

  if (options.mainText !== null) {
    /* BEGIN Name text render */

    if (options.personName !== null) {
      mainTextMarginBottom += nameTextExtraBottomMargin;

      let styles = {
        0: {},
      };

      for (let position = 0; position < options.personName.length; position++) {
        styles[0][position] = {
          fontWeight: "bold",
        };
      }

      personNameText = new fabric.Text(options.personName, {
        left: textMarginLeft,
        top: canvas.height - mainTextMarginBottom + nameTextMarginTop,
        fontFamily: "Roboto Condensed",
        fontSize: bottomTextSize,
        styles: styles,
        fill: options.colors.baseText.value,
        selectable: false,
        zIndex: 10,
      });

      if (options.personPosition !== null) {
        personInfoSeparator = new fabric.Rect({
          left:
            personNameText.left + personNameText.width + positionTextSideGap,
          width: positionTextSeparatorWidth,
          fill: options.colors.baseText.value,
          selectable: false,
          zIndex: 10,
        });

        personPositionText = new fabric.Textbox(options.personPosition, {
          left:
            personInfoSeparator.left +
            personInfoSeparator.width +
            positionTextSideGap,
          top: personNameText.top,
          width: positionTextMaxWidth,
          fontFamily: "Roboto Condensed",
          fontSize: bottomTextSize,
          fill: options.colors.baseText.value,
          selectable: false,
          zIndex: 10,
        });

        checkTextBoxHeight(personPositionText, 2);

        if (personPositionText._textLines.length === 2) {
          mainTextMarginBottom += nameTextExtraBottomMargin;
          personNameText.set({
            top: personNameText.top - nameTextExtraBottomMargin,
          });
          personPositionText.set({
            top: personPositionText.top - nameTextExtraBottomMargin,
          });
        }

        canvas.add(personPositionText);

        personInfoSeparator.set({ top: personPositionText.top });
        personInfoSeparator.set({ height: personPositionText.height });
        canvas.add(personInfoSeparator);

        canvas.renderAll();
      }

      canvas.add(personNameText);
    }

    /* END Name text render */

    /* BEGIN Main text render */

    const mainTextWidth = canvas.width - textMarginLeft - textMarginRight;

    const highlightedData = transformHighlightedText(
      options.mainText,
      mainTextSize,
      mainTextWidth,
      "Bebas Neue",
      options.colors.highlight.value,
      options.colors.highlightedText.value,
      { padWhenDiacritics: true },
    );

    mainTextBox = new PaddedHighlightingTextbox(highlightedData.text, {
      width: canvas.width,
      left: textMarginLeft,
      textAlign: "left",
      fontFamily: "Bebas Neue",
      fontSize: mainTextSize,
      lineHeight: mainTextLineHeight,
      fill: options.colors.baseText.value,
      styles: highlightedData.styles,
      selectable: false,
      highlightPadding: canvas.height * 0.003,
      zIndex: 10,
    });

    checkTextBoxHeight(mainTextBox, 3);

    canvas.add(mainTextBox);

    const mainTextBoxTop =
      canvas.height - mainTextBox.height - mainTextMarginBottom;

    mainTextBox.top = mainTextBoxTop - highlightedData.paddingBottom;

    canvas.renderAll();

    /* END Main text render */

    /* BEGIN Arrow render */

    arrow = new fabric.Polygon(
      [
        { x: 0, y: 0 },
        { x: arrowThickness, y: 0 },
        {
          x: arrowWidth,
          y: Math.ceil(arrowHeight) / 2,
        },
        {
          x: arrowThickness,
          y: arrowHeight,
        },
        { x: 0, y: arrowHeight },
        {
          x: arrowWidth - arrowThickness,
          y: Math.ceil(arrowHeight) / 2,
        },
        { x: 0, y: 0 },
      ],
      {
        top: mainTextBoxTop + arrowMarginTop,
        left:
          arrowMarginLeft +
          (options.mainText[0] === "*" ? arrowMarginLeftExtra : 0),
        fill: options.colors.arrow.value,
        selectable: false,
        zIndex: 10,
      },
    );

    canvas.add(arrow);

    /* END Arrow render */

    /* BEGIN Main text background render */

    const backgroundHeight =
      canvas.height - mainTextBoxTop + mainTextBackgroundMarginTop;

    mainTextBoxBackground = new fabric.Rect({
      width: canvas.width + 30, // FIXME: Whhhhyyyyyy????
      height: backgroundHeight * options.gradientHeightMultiplier,
      left: -20,
      top:
        mainTextBoxTop -
        mainTextBackgroundMarginTop -
        backgroundHeight * (options.gradientHeightMultiplier - 1),
      fill: new fabric.Gradient({
        type: "linear",
        gradientUnits: "pixels",
        coords: {
          x1: 0,
          y1: 0,
          x2: 0,
          y2: backgroundHeight * options.gradientHeightMultiplier,
        },
        colorStops: [
          {
            offset: 1,
            color: options.colors.background.value,
          },
          {
            offset: 0.45,
            color: options.colors.background.value,
          },
          {
            offset: 0,
            color: `${options.colors.background.value}00`,
          },
        ],
      }),
      selectable: false,
      zIndex: 9,
    });

    canvas.add(mainTextBoxBackground);

    /* END Main text background render */
  }

  /* BEGIN Logo render */

  // A logo is provided, and it either hasn't been rendered yet or is a new one.
  const createNewLogo =
    (options.logoImage !== null &&
      (logoImage === null ||
        (options.logoImage !== null &&
          options.logoImage !== logoImage._element))) ||
    previousLogoPosition != options.logoPosition.id;

  previousLogoPosition = options.logoPosition.id;

  if (createNewLogo) {
    canvas.remove(logoImage);

    logoImage = new fabric.Image(options.logoImage, { selectable: false });
    logoImage.scaleToWidth(logoWidth);

    if (options.logoPosition.id == "top-right") {
      logoImage.set({
        left: canvas.width - logoWidth - logoSideMargin,
        top: logoSideMargin,
        zIndex: 11,
      });
    } else {
      logoImage.set({
        left: logoSideMargin,
        top: logoSideMargin,
        zIndex: 11,
      });
    }

    canvas.add(logoImage);
  }

  /* END Logo render */

  /* BEGIN Contracted by render */

  if (options.contractedBy !== null) {
    contractedByTextbox = new fabric.Textbox(options.contractedBy, {
      left:
        canvas.width - contractedByTextMaxWidth - contractedByTextSidesMargin,
      top: canvas.height - contractedByTextSidesMargin - contractedByTextSize,
      width: contractedByTextMaxWidth,
      fontFamily: "Roboto Condensed",
      fontSize: contractedByTextSize,
      textAlign: "right",
      fill: options.colors.contractedByText.value,
      selectable: false,
      zIndex: 10,
    });

    checkTextBoxHeight(contractedByTextbox, 1);

    canvas.add(contractedByTextbox);
  }

  /* END Contracted by render */

  /* BEGIN Main image render */

  if (
    options.mainImage !== null &&
    (!canvas.contains(mainImage) ||
      mainImage === null ||
      options.mainImage.src !== mainImageSource)
  ) {
    if (mainImage !== null) {
      canvas.remove(mainImage);
    }

    mainImage = new fabric.Image(options.mainImage, {
      left: 0,
      top: 0,
      zIndex: 0,
    });

    mainImage.controls = {
      ...fabric.Image.prototype.controls,
      mtr: new fabric.Control({ visible: false }),
    };

    if (mainImage.width >= mainImage.height) {
      mainImage.scaleToHeight(canvas.height);
    } else {
      mainImage.scaleToWidth(canvas.width);
    }

    canvas.add(mainImage);
    mainImageSource = options.mainImage.src;
    // canvas.centerObject(mainImage)
  } else if (mainImage !== null && options.mainImage === null) {
    canvas.remove(mainImage);
  }

  /* END Main image render */

  sortObjects(canvas);
};

export default redraw;
