import { fabric } from "fabric";
import {
  clearObjects,
  sortObjects,
  transformHighlightedText,
  checkTextBoxHeight,
} from "../../components/canvas/utils";
import { PaddedHighlightingTextbox } from "../../components/canvas/textbox";
import overlayURL from "../../assets/template/event_poster/base.png";

let mainImage = null;
let mainImageSource = null;
let overlayImage = null;
let pointerDownEventAssigned = false;
let eventDateText = null;
let eventLocationText = null;
let mainText = null;
let firstColumn = null;
let secondColumn = null;

let contractedByTextbox = null;

const removeDownEventListener = () => {
  document
    .getElementsByClassName("upper-canvas")[0]
    .removeEventListener("pointerdown", canvasPointerDownEvent);
};

let upEventFunction = null;
let canvasPointerDownEvent = null;

const redraw = async (canvas, options) => {
  clearObjects(
    [
      eventDateText,
      eventLocationText,
      contractedByTextbox,
      mainText,
      firstColumn,
      secondColumn,
    ],
    canvas,
  );

  const bottomMarginText = 200;
  const bottomFontSize = 90;

  const mainTextMarginBottom = 2200;
  const mainTextSize = 600;
  const mainTextMarginSides = 250;

  const secondaryTextSize = 300;
  const secondaryTextMarginBottom = 1600;
  const secondaryTextMarginSides = 325;

  const columnsMarginTop = -1000;
  const columnsMarginBetween = 100;
  const columnsMaxWidth = 1500;
  const columnTextSize = 130;
  const columnLineHeight = 1;

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

  document
    .getElementsByClassName("upper-canvas")[0]
    .removeEventListener("pointerup", upEventFunction);
  document
    .getElementsByClassName("upper-canvas")[0]
    .removeEventListener("pointerout", upEventFunction);
  document
    .getElementsByClassName("upper-canvas")[0]
    .removeEventListener("pointercancel", upEventFunction);

  canvas.preserveObjectStacking = true;

  /* 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: 10,
    });

    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)

    removeDownEventListener();
    pointerDownEventAssigned = false;
  } else if (mainImage !== null && options.mainImage === null) {
    canvas.remove(mainImage);

    removeDownEventListener();
    pointerDownEventAssigned = false;
  }

  /* END Main image render */

  /* BEGIN Overlay render */

  if (overlayImage === null) {
    overlayImage = new Image();

    await new Promise((resolve) => {
      overlayImage.onload = () => {
        resolve();
      };

      overlayImage.src = overlayURL;
    });

    overlayImage = new fabric.Image(overlayImage, {
      top: -20, // FIXME: Why???? Fabric.js, what are you trying to tell me?!
      left: -20,
      zIndex: 20,
      selectable: false,
    });
    overlayImage.scaleToWidth(canvas.width + 22);

    canvas.add(overlayImage);
  }

  /* END Overlay render */

  /* BEGIN Main text render */

  if (options.mainText !== null) {
    mainText = new fabric.Textbox(options.mainText, {
      left: mainTextMarginSides,
      top: canvas.height - mainTextMarginBottom,
      width: canvas.width - mainTextMarginSides * 2,
      textAlign: "center",
      fontFamily: "Bebas Neue",
      fontSize: mainTextSize,
      fill: "#fec900",
      selectable: false,
      zIndex: 40,
    });

    // Keep to a single line no matter what
    canvas.add(mainText);

    while (mainText._textLines.length > 1) {
      mainText.set({
        fontSize: mainText.fontSize - 20,
        top: mainText.top + 10,
      });
      canvas.renderAll();
    }
  }

  /* END Main text render */

  /* BEGIN Event date text render */

  if (options.eventDate !== null) {
    eventDateText = new fabric.Text(options.eventDate, {
      left: secondaryTextMarginSides,
      top: canvas.height - secondaryTextMarginBottom,
      fontFamily: "Bebas Neue",
      fontSize: secondaryTextSize,
      fill: "#fec900",
      selectable: false,
      zIndex: 40,
    });

    canvas.add(eventDateText);
  }

  /* END Event date text render */

  /* BEGIN Event location text render */

  if (options.eventLocation !== null) {
    eventLocationText = new fabric.Text(options.eventLocation, {
      left: canvas.width - secondaryTextMarginSides,
      top: canvas.height - secondaryTextMarginBottom,
      fontFamily: "Bebas Neue",
      fontSize: secondaryTextSize,
      textAlign: "right",
      fill: "#fec900",
      selectable: false,
      zIndex: 40,
    });

    canvas.add(eventLocationText);

    eventLocationText.set({
      left: eventLocationText.left - eventLocationText.width,
    });
    canvas.renderAll();
  }

  /* END Event location text render */

  /* BEGIN Column text render */

  if (options.firstColumn !== null) {
    firstColumn = new fabric.Textbox(options.firstColumn, {
      left: mainTextMarginSides,
      top: canvas.height + columnsMarginTop,
      width: columnsMaxWidth,
      fontFamily: "Roboto Condensed",
      fontSize: columnTextSize,
      lineHeight: columnLineHeight,
      fill: "#000",
      selectable: false,
      zIndex: 40,
    });

    canvas.add(firstColumn);
  }

  if (options.secondColumn !== null) {
    secondColumn = new fabric.Textbox(options.secondColumn, {
      left: mainTextMarginSides + columnsMarginBetween + columnsMaxWidth,
      top: canvas.height + columnsMarginTop,
      width: columnsMaxWidth,
      fontFamily: "Roboto Condensed",
      fontSize: columnTextSize,
      lineHeight: columnLineHeight,
      fill: "#000",
      selectable: false,
      zIndex: 40,
    });

    canvas.add(secondColumn);
  }

  /* END Column text render */

  /* BEGIN Contracted by render */

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

    checkTextBoxHeight(contractedByTextbox, 1);

    canvas.add(contractedByTextbox);
  }

  /* END Contracted by render */

  sortObjects(canvas);

  canvasPointerDownEvent = (event) => {
    let activeObject = canvas.getActiveObject();

    if (activeObject === null) {
      return;
    }

    // if (activeObject._element.src == mainImage._element.src) {
    // return
    // }

    canvas.remove(overlayImage);
    overlayImage = null;
  };

  if (!pointerDownEventAssigned) {
    document
      .getElementsByClassName("upper-canvas")[0]
      .addEventListener("pointerdown", canvasPointerDownEvent);

    pointerDownEventAssigned = true;
  }

  upEventFunction = (event) => {
    redraw(canvas, options);
  };

  document
    .getElementsByClassName("upper-canvas")[0]
    .addEventListener("pointerup", upEventFunction);

  document
    .getElementsByClassName("upper-canvas")[0]
    .addEventListener("pointerout", upEventFunction);

  document
    .getElementsByClassName("upper-canvas")[0]
    .addEventListener("pointercancel", upEventFunction);
};

export default redraw;
