///////////////////////////////////////////////////////////////////////////////
// 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 { REVISION } from "three";
import { IComponent } from "@inweb/viewer-core";
import type { Viewer } from "../Viewer";

export class InfoComponent implements IComponent {
  protected viewer: Viewer;
  private startTime: number;
  private beginTime: number;
  private prevTime: number;
  private frames: number;

  constructor(viewer: Viewer) {
    this.viewer = viewer;
    this.startTime = 0;
    this.beginTime = performance.now();
    this.prevTime = performance.now();
    this.frames = 0;
    this.viewer.addEventListener("initialize", this.initialize);
    this.viewer.addEventListener("clear", this.clear);
    this.viewer.addEventListener("optionschange", this.optionsChange);
    this.viewer.addEventListener("geometrystart", this.geometryStart);
    this.viewer.addEventListener("databasechunk", this.databaseChunk);
    this.viewer.addEventListener("geometryend", this.geometryEnd);
    this.viewer.addEventListener("resize", this.resize);
    this.viewer.addEventListener("render", this.render);
    this.viewer.addEventListener("animate", this.animate);
  }

  dispose() {
    this.viewer.removeEventListener("initialize", this.initialize);
    this.viewer.removeEventListener("clear", this.clear);
    this.viewer.removeEventListener("optionschange", this.optionsChange);
    this.viewer.removeEventListener("geometrystart", this.geometryStart);
    this.viewer.removeEventListener("databasechunk", this.databaseChunk);
    this.viewer.removeEventListener("geometryend", this.geometryEnd);
    this.viewer.removeEventListener("resize", this.resize);
    this.viewer.removeEventListener("render", this.render);
    this.viewer.addEventListener("animate", this.animate);
  }

  initialize = () => {
    try {
      const gl = this.viewer.renderer.getContext();
      const dbgInfo = gl.getExtension("WEBGL_debug_renderer_info");
      if (dbgInfo) {
        this.viewer.info.system.webglRenderer = gl.getParameter(dbgInfo.UNMASKED_RENDERER_WEBGL);
        this.viewer.info.system.webglVendor = gl.getParameter(dbgInfo.UNMASKED_VENDOR_WEBGL);
      }
    } catch (error) {
      console.error("Error reading WebGL info.", error);
    }

    console.log("THREE.WebGLRenderer:", REVISION);
    console.log("WebGL Renderer:", this.viewer.info.system.webglRenderer);
    console.log("WebGL Vendor:", this.viewer.info.system.webglVendor);

    this.resize();

    this.optionsChange({ data: this.viewer.options });
  };

  clear = () => {
    this.viewer.info.performance.timeToFirstRender = 0;
    this.viewer.info.performance.loadTime = 0;

    this.viewer.info.scene.objects = 0;
    this.viewer.info.scene.triangles = 0;
    this.viewer.info.scene.points = 0;
    this.viewer.info.scene.lines = 0;
    this.viewer.info.scene.edges = 0;

    this.viewer.info.optimizedScene.objects = 0;
    this.viewer.info.optimizedScene.triangles = 0;
    this.viewer.info.optimizedScene.points = 0;
    this.viewer.info.optimizedScene.lines = 0;
    this.viewer.info.optimizedScene.edges = 0;

    this.viewer.info.memory.geometries = 0;
    this.viewer.info.memory.geometryBytes = 0;
    this.viewer.info.memory.textures = 0;
    this.viewer.info.memory.textureBytes = 0;
    this.viewer.info.memory.materials = 0;
    this.viewer.info.memory.totalEstimatedGpuBytes = 0;
    this.viewer.info.memory.usedJSHeapSize = 0;
  };

  optionsChange = ({ data: options }) => {
    if (options.antialiasing === false) this.viewer.info.render.antialiasing = "";
    else if (options.antialiasing === true) this.viewer.info.render.antialiasing = "mxaa";
    else this.viewer.info.render.antialiasing = options.antialiasing;
  };

  geometryStart = () => {
    this.startTime = performance.now();
  };

  databaseChunk = () => {
    this.viewer.info.performance.timeToFirstRender += performance.now() - this.startTime;

    console.log("Time to first render:", this.viewer.info.performance.timeToFirstRender, "ms");
  };

  geometryEnd = () => {
    const model = this.viewer.models[this.viewer.models.length - 1];
    const info = model.getInfo();

    this.viewer.info.scene.objects += info.scene.objects;
    this.viewer.info.scene.triangles += info.scene.triangles;
    this.viewer.info.scene.points += info.scene.points;
    this.viewer.info.scene.lines += info.scene.lines;
    this.viewer.info.scene.edges += info.scene.edges;

    this.viewer.info.optimizedScene.objects += info.optimizedScene.objects;
    this.viewer.info.optimizedScene.triangles += info.optimizedScene.triangles;
    this.viewer.info.optimizedScene.points += info.optimizedScene.points;
    this.viewer.info.optimizedScene.lines += info.optimizedScene.lines;
    this.viewer.info.optimizedScene.edges += info.optimizedScene.edges;

    this.viewer.info.memory.geometries += info.memory.geometries;
    this.viewer.info.memory.geometryBytes += info.memory.geometryBytes;
    this.viewer.info.memory.textures += info.memory.textures;
    this.viewer.info.memory.textureBytes += info.memory.textureBytes;
    this.viewer.info.memory.materials += info.memory.materials;
    this.viewer.info.memory.totalEstimatedGpuBytes += info.memory.totalEstimatedGpuBytes;

    const memory = performance["memory"];
    if (memory) this.viewer.info.memory.usedJSHeapSize = memory.usedJSHeapSize;

    this.viewer.info.performance.loadTime += performance.now() - this.startTime;

    console.log("Number of objects:", info.scene.objects);
    console.log("Number of objects after optimization:", info.optimizedScene.objects);
    console.log("Total geometry size:", info.memory.totalEstimatedGpuBytes / (1024 * 1024), "MB");

    console.log("File load time:", this.viewer.info.performance.loadTime, "ms");
  };

  resize = () => {
    const { width, height } = this.viewer.canvas;
    this.viewer.info.render.viewport.width = width;
    this.viewer.info.render.viewport.height = height;
  };

  render = () => {
    this.viewer.info.render.drawCalls = this.viewer.renderer.info.render.calls;
    this.viewer.info.render.triangles = this.viewer.renderer.info.render.triangles;
    this.viewer.info.render.points = this.viewer.renderer.info.render.points;
    this.viewer.info.render.lines = this.viewer.renderer.info.render.lines;
  };

  animate = () => {
    const time = performance.now();

    this.viewer.info.performance.frameTime = Math.round(time - this.beginTime);
    this.beginTime = time;

    this.frames++;
    if (time - this.prevTime >= 1000) {
      this.viewer.info.performance.fps = Math.round((this.frames * 1000) / (time - this.prevTime));
      this.prevTime = time;
      this.frames = 0;
    }
  };
}
