import { i18n } from '@lingui/core';
import { t } from '@lingui/macro';
import { round } from 'lodash-es';
import { v4 as uuidv4 } from 'uuid';
import { ShapeConfig, ShapeTypes } from '../components/annotator/types';
import { testingUser } from '../constants/variable';
import { PRECISION } from '../consts';
import {
  BoundingBox,
  DriverLicenseResult,
  IDCardResult,
  InvoiceResult,
  InvoiceResultDocClsBase,
  InvoiceResultDocCls,
  OtherDocumentsResult,
  TemplateOcrResult,
} from '../models';
import { ConsoleSqlOutlined } from '@ant-design/icons';

// export function extractShapesFromInvoiceResults(
//   results: InvoiceResult,
// ): ShapeConfig[] {
//   const { fields } = results;
//   return fields.map(({ label, value, box: [x1, y1, x2, y2], confidence }) => {
//     return {
//       id: uuidv4(),
//       type: ShapeTypes.RECTANGLE,
//       x: x1,
//       y: y1,
//       width: x2 - x1,
//       height: y2 - y1,
//       stroke: 'red',
//       fill: 'rgba(255,0,0,0.2)',
//       isAnchor: false,
//       strokeWidth: 4,
//       data: {
//         label,
//         value,
//         confidentScore: confidence,
//       },
//     };
//   });
// }

export function extractShapesFromInvoiceResults(
  results: InvoiceResultDocCls,
): ShapeConfig[] {
  const { document } = results;
  let result = [];
  
  console.log(document)

  document[0].content.forEach((cont) => {
    console.log("-------")
    console.log(cont.label)
    console.log(cont.value)
    console.log("-------")
    // if (!cont.value) {
    //   return;
    // }
    let value = Array.isArray(cont.value) ? cont.value.join('\n') : cont.value;
    result.push({
      id: uuidv4(),
      type: ShapeTypes.RECTANGLE,
      x: 0,
      y: 0,
      width:1,
      height: 1,
      stroke: 'red',
      fill: 'rgba(255,0,0,0.2)',
      isAnchor: false,
      strokeWidth: 4,
      data: {
        label: cont.label,
        value: value,
      },
    });
  });
  return result;
}

export function extractShapesFromTemplateData(
  boxs: Array<BoundingBox>,
  anchors: Array<BoundingBox>,
): ShapeConfig[] {
  let result = [];

  boxs.forEach((box) => {
    result.push({
      id: box.id.toString(),
      type: ShapeTypes.RECTANGLE,
      x: round(Number(box.coordinates[0]), PRECISION),
      y: round(Number(box.coordinates[1]), PRECISION),
      width: round(
        Number(box.coordinates[2]) - Number(box.coordinates[0]),
        PRECISION,
      ),
      height: round(
        Number(box.coordinates[3]) - Number(box.coordinates[1]),
        PRECISION,
      ),
      stroke: 'red',
      fill: 'rgba(255,0,0,0.2)',
      isAnchor: false,
      strokeWidth: 4,
      data: {
        label: box.name,
        value: '',
      },
    });
  });

  if (!!anchors) {
    anchors.forEach((box, index) => {
      result.push({
        id: box.id.toString(),
        type: ShapeTypes.RECTANGLE,
        x: round(Number(box.coordinates[0]), PRECISION),
        y: round(Number(box.coordinates[1]), PRECISION),
        width: round(
          Number(box.coordinates[2]) - Number(box.coordinates[0]),
          PRECISION,
        ),
        height: round(
          Number(box.coordinates[3]) - Number(box.coordinates[1]),
          PRECISION,
        ),
        stroke: 'rgb(0,255,0)',
        fill: 'rgba(0,255,0,0.2)',
        isAnchor: true,
        strokeWidth: 4,
        data: {
          label: `Anchor ${index + 1}`,
          value: '',
        },
      });
    });
  }

  return result;
}

export function extractShapesFromIDCardResults(
  results: IDCardResult,
): ShapeConfig[] {
  const { batch_preds, batch_words, batch_true_boxes } = results.content;

  return batch_true_boxes.map(([x1, y1, x2, y2], index) => {
    return {
      id: uuidv4(),
      type: ShapeTypes.RECTANGLE,
      x: x1,
      y: y1,
      width: x2 - x1,
      height: y2 - y1,
      stroke: 'red',
      fill: 'rgba(255,0,0,0.2)',
      isAnchor: false,
      strokeWidth: 4,
      data: {
        label: batch_preds[index],
        value: batch_words[index],
      },
    };
  });
}

export function extractShapesFromDriverLicenseResults(
  results: DriverLicenseResult,
): ShapeConfig[] {
  const { batch_preds, batch_words, batch_true_boxes } = results.content;

  return batch_true_boxes.map(([x1, y1, x2, y2], index) => {
    return {
      id: uuidv4(),
      type: ShapeTypes.RECTANGLE,
      x: x1,
      y: y1,
      width: x2 - x1,
      height: y2 - y1,
      stroke: 'red',
      fill: 'rgba(255,0,0,0.2)',
      isAnchor: false,
      strokeWidth: 4,
      data: {
        label: batch_preds[index],
        value: batch_words[index],
      },
    };
  });
}

export function extractShapesFromOtherDocumentsResults(
  results: OtherDocumentsResult,
): ShapeConfig[] {
  const { texts } = results.content;

  return [
    {
      id: uuidv4(),
      type: ShapeTypes.RECTANGLE,
      x: 0,
      y: 0,
      width: 0,
      height: 0,
      visible: false,
      data: {
        label: 'text',
        value: texts.join(''),
      },
    },
  ];
}

export function shapesToCsv(shapes: ShapeConfig[]) {
  const data: [string, string][] = [[t`Label`, t`Value`]];
  shapes.forEach((shape) => {
    data.push([i18n._(shape.data.label) || shape.data.label, shape.data.value]);
  });

  return data;
}

export function shapesToStringData(shapes: ShapeConfig[]) {
  let listName = [];
  let listBoundingBox = [];
  let listAnchor = [];

  shapes.forEach((rec) => {
    if (rec.isAnchor) {
      let arrCoor = [0, 0, 0, 0];
      Object.entries(rec).forEach(([label, value]) => {
        switch (label) {
          case 'x':
            arrCoor[0] += Number(value);
            arrCoor[2] += Number(value);
            break;
          case 'y':
            arrCoor[1] += Number(value);
            arrCoor[3] += Number(value);
            break;
          case 'width':
            arrCoor[2] += Number(value);
            break;
          case 'height':
            arrCoor[3] += Number(value);
            break;
        }
      });
      listAnchor.push(arrCoor.map((item) => round(item, PRECISION)).join(','));
    } else {
      let arrCoor = [0, 0, 0, 0];
      Object.entries(rec).forEach(([label, value]) => {
        switch (label) {
          case 'x':
            arrCoor[0] += Number(value);
            arrCoor[2] += Number(value);
            break;
          case 'y':
            arrCoor[1] += Number(value);
            arrCoor[3] += Number(value);
            break;
          case 'width':
            arrCoor[2] += Number(value);
            break;
          case 'height':
            arrCoor[3] += Number(value);
            break;
        }
      });
      listBoundingBox.push(
        arrCoor.map((item) => round(item, PRECISION)).join(','),
      );
      listName.push(rec.data?.label);
    }
  });

  return {
    listNameBox: listName.join(testingUser.uniqueComma),
    listBBox: listBoundingBox.join(';'),
    listAnchor: listAnchor.join(';'),
  };
}

export function extractShapesFromTemplateOcrResults(
  results: TemplateOcrResult,
  boxs: Array<BoundingBox>,
): ShapeConfig[] {
  let result = [];

  boxs.forEach((box) => {
    result.push({
      id: uuidv4(),
      type: ShapeTypes.RECTANGLE,
      x: Number(box.coordinates[0]),
      y: Number(box.coordinates[1]),
      width: Number(box.coordinates[2]) - Number(box.coordinates[0]),
      height: Number(box.coordinates[3]) - Number(box.coordinates[1]),
      stroke: 'red',
      fill: 'rgba(255,0,0,0.2)',
      isAnchor: false,
      strokeWidth: 4,
      data: {
        label: box.name,
        value: results.content[box.name],
      },
    });
  });

  return result;
}

export function shapesToTemplateData(shapes: ShapeConfig[]) {
  return shapes.map((shape) => {
    return {
      ...shape,
      x: round(shape.x, PRECISION),
      y: round(shape.y, PRECISION),
      width: round(shape.width, PRECISION),
      height: round(shape.height, PRECISION),
    };
  });
}
