///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2002-2025, Open Design Alliance (the "Alliance").
// All rights reserved.
//
// This software and its documentation and related materials are owned by
// the Alliance. The software may only be incorporated into application
// programs owned by members of the Alliance, subject to a signed
// Membership Agreement and Supplemental Software License Agreement with the
// Alliance. The structure and organization of this software are the valuable
// trade secrets of the Alliance and its suppliers. The software is also
// protected by copyright law and international treaty provisions. Application
// programs incorporating this software must include the following statement
// with their copyright notices:
//
//   This application incorporates Open Design Alliance software pursuant to a
//   license agreement with Open Design Alliance.
//   Open Design Alliance Copyright (C) 2002-2025 by Open Design Alliance.
//   All rights reserved.
//
// By use of this software, its documentation or related materials, you
// acknowledge and accept the above terms.
///////////////////////////////////////////////////////////////////////////////

import { Model, File, Assembly } from "@inweb/client";
import { Viewer } from "../Viewer";
import { composeMatrixFromTransform } from "./ApplyModelTransform";

function isTemplateModel(modelPtr) {
  return modelPtr.getName()[0] === "$";
}

export async function autoTransformAllModelsToCentralPoint(
  viewer: Viewer,
  model: Model | File | Assembly
): Promise<void> {
  if (!viewer.visualizeJs) return;
  if (!model.getModelTransformMatrix) return; // Model.getModelTransformMatrix() since 24.3.14

  const visLib = viewer.visLib();
  const visViewer = visLib.getViewer();

  const viewExt = visViewer.getActiveExtents();
  const centralPoint = viewExt.center();

  const modelItr = visViewer.getModelIterator();
  for (; !modelItr.done(); modelItr.step()) {
    const modelPtr = modelItr.getModel();

    if (!isTemplateModel(modelPtr)) {
      const ext = modelPtr.getExtents();

      const unitsMatrix = modelPtr.getUnitsMatrix();
      ext.transformBy(modelPtr.getUnitsMatrix()); // ext in wcs

      const unitsMatrixInvert = modelPtr.getUnitsMatrix().invert();

      const center = ext.center();
      const scale = 1.0;

      const scaleMatrix = new visLib.Matrix3d();
      const translateMatrix = new visLib.Matrix3d();

      translateMatrix.setTranslation([
        centralPoint[0] - center[0],
        centralPoint[1] - center[1],
        centralPoint[2] - center[2],
      ]);
      scaleMatrix.setToScaling(scale, centralPoint);

      const resMatrixWithUnits = unitsMatrixInvert
        .postMultBy(scaleMatrix)
        .postMultBy(translateMatrix)
        .postMultBy(unitsMatrix);

      const resScale = resMatrixWithUnits.scale();
      const transform = {
        translate: {
          x: resMatrixWithUnits.get(0, 3) - (1 - resScale) * center[0],
          y: resMatrixWithUnits.get(1, 3) - (1 - resScale) * center[1],
          z: resMatrixWithUnits.get(2, 3) - (1 - resScale) * center[2],
        },
        rotation: { x: 0, y: 0, z: 1, angle: 0.0 },
        scale: resScale,
      };

      const matrix = composeMatrixFromTransform(transform, center, visLib);
      modelPtr.setModelingMatrix(matrix, true);

      centralPoint[0] += Math.abs(ext.max()[0] - ext.min()[0]) * resScale;

      await model.setModelTransformMatrix(modelPtr.getDatabaseHandle(), transform);
    }

    modelPtr.delete();
  }
  modelItr.delete();

  visViewer.clearViewExtentsCache?.();

  viewer.update();
}
