import { i18n } from '@lingui/core';
import { t } from '@lingui/macro';
import { isEqual } from 'lodash-es';
import { ShapeConfig } from '../components/annotator/types';
import { testingUser } from '../constants/variable';
import { TemplateWithShapes } from '../models/template';

export function validateTemplate(shapes: ShapeConfig[]) {
  let boundingBox = shapes.filter((item) => item.isAnchor !== true);

  if (boundingBox.length === 0)
    return {
      status: false,
      message: t(i18n)`Please draw at least 1 box of extracted field`,
    };

  if (boundingBox.length > testingUser.maxBoundingBox)
    return {
      status: false,
      message: t(
        i18n,
      )`The number of created information fields exceeds the maximum number of supported fields on a template (${testingUser.maxBoundingBox} fields).`,
    };

  let checkEmptyLabel = false;
  let checkLabelMaxLength = false;

  boundingBox.forEach((box) => {
    if (box.data.label === '') checkEmptyLabel = true;
    if (box.data.label.length > 255) checkLabelMaxLength = true;
  });

  if (checkEmptyLabel)
    return {
      status: false,
      message: t(i18n)`Please do not leave the label of extracted fields empty`,
    };

  if (checkLabelMaxLength)
    return {
      status: false,
      message: t(
        i18n,
      )`Label of extracted field must not have more than 255 characters`,
    };

  return {
    status: true,
    message: '',
  };
}

export function isTemplateChanged(
  originalTemplate: TemplateWithShapes,
  currentTemplate: TemplateWithShapes,
) {
  if (originalTemplate?.shapes.length !== currentTemplate?.shapes.length)
    return true;

  for (let shape of currentTemplate.shapes) {
    let oldShape = originalTemplate.shapes.filter(
      (oriShape) => oriShape.id === shape.id,
    )[0];
    if (!oldShape) return true;

    if (!isEqual(shape, oldShape)) return true;
  }

  return false;
}
