///////////////////////////////////////////////////////////////////////////////
// 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 { IHttpClient } from "./IHttpClient";
import { Endpoint } from "./Endpoint";
import { FetchError } from "./FetchError";
import { ICdaNode, IFileReferences } from "./IFile";
import { IAssociatedFileData, IAssemblyVersionInfo, IModelTransformMatrix } from "./IAssembly";
import { IShortUserDesc } from "./IUser";
import { Model } from "./Model";
import { ClashTest } from "./ClashTest";
import { ISharedLinkPermissions } from "./ISharedLink";
import { SharedLink } from "./SharedLink";
import { waitFor, userFullName, userInitials } from "./Utils";

/**
 * Provides properties and methods for obtaining information about an assembly on the Open Cloud Server
 * and managing its data.
 */
export class Assembly extends Endpoint {
  private _data: any;

  /**
   * @param data - Raw assembly data received from the server. For more information, see
   *   {@link https://cloud.opendesign.com/docs//pages/server/api.html#Assemblies | Open Cloud Assemblies API}.
   * @param httpClient - HTTP client instance used to send requests to the REST API server.
   */
  constructor(data: any, httpClient: IHttpClient) {
    super(`/assemblies/${data.id}`, httpClient);
    this.data = data;
  }

  // Reserved for future use

  get activeVersion(): number {
    return this.data.activeVersion;
  }

  /**
   * List of unique files from which the assembly was created.
   *
   * @readonly
   */
  get associatedFiles(): IAssociatedFileData[] {
    return this.data.associatedFiles;
  }

  /**
   * Assembly creation time (UTC) in the format specified in
   * {@link https://www.wikipedia.org/wiki/ISO_8601 | ISO 8601}.
   *
   * @readonly
   */
  get created(): string {
    return this.data.created;
  }

  /**
   * Returns the raw assembly data received from the server. For more information, see
   * {@link https://cloud.opendesign.com/docs//pages/server/api.html#Assemblies | Open Cloud Assemblies API}.
   */
  get data(): any {
    return this._data;
  }

  private set data(value: any) {
    this._data = value;
    this._data.owner.avatarUrl = `${this.httpClient.serverUrl}/users/${this._data.owner.userId}/avatar`;
    this._data.owner.fullName = userFullName(this._data.owner);
    this._data.owner.initials = userInitials(this._data.owner.fullName);
    // associatedFiles since 23.12
    this._data.associatedFiles ??= [];
    this._data.associatedFiles.forEach((file) => (file.link = `${this.httpClient.serverUrl}/files/${file.fileId}`));
  }

  /**
   * List of file IDs from which the assembly was created.
   *
   * @readonly
   */
  get files(): string[] {
    return this.data.files;
  }

  /**
   * Assembly geometry data type:
   *
   * - `vsfx` - `VSFX` format, assembly can be opened in `VisualizeJS` viewer.
   *
   * Returns an empty string if the geometry data is not yet ready.
   */
  get geometryType(): string {
    return this.status === "done" ? "vsfx" : "";
  }

  /**
   * Unique assembly ID.
   *
   * @readonly
   */
  get id(): string {
    return this.data.id;
  }

  /**
   * Assembly name.
   */
  get name(): string {
    return this.data.name;
  }

  set name(value: string) {
    this.data.name = value;
  }

  // Reserved for future use

  get originalAssemblyId(): string {
    return this.data.originalAssemblyId;
  }

  /**
   * Assembly owner information.
   *
   * @readonly
   */
  get owner(): IShortUserDesc {
    return this.data.owner;
  }

  // Reserved for future use

  get previewUrl(): string {
    return this.data.previewUrl || "";
  }

  /**
   * List of assembly related job IDs.
   *
   * @readonly
   */
  get relatedJobs(): string[] {
    return this.data.relatedJobs;
  }

  /**
   * Assembly geometry data and properties status. Can be `waiting`, `inprogress`, `done` or `failed`.
   *
   * An assemblies without geometry data cannot be opened in viewer.
   *
   * @readonly
   */
  get status(): string {
    return this.data.status;
  }

  /**
   * Assembly type. Returns an `assembly` string.
   *
   * @readonly
   */
  get type(): string {
    return "assembly";
  }

  // Reserved for future use

  get version(): number {
    return this.data.version;
  }

  get versions(): IAssemblyVersionInfo[] {
    return this.data.versions;
  }

  /**
   * Reloads assembly data from the server.
   */
  async checkout(): Promise<this> {
    const response = await this.get("");
    this.data = await response.json();
    return this;
  }

  /**
   * Updates assembly data on the server.
   *
   * @param data - Raw assembly data. For more information, see
   *   {@link https://cloud.opendesign.com/docs//pages/server/api.html#Assemblies | Open Cloud Assemblies API}.
   */
  async update(data: any): Promise<this> {
    const response = await this.put("", data);
    this.data = await response.json();
    return this;
  }

  /**
   * Deletes an assembly from the server.
   *
   * @returns Returns the raw data of a deleted assembly. For more information, see
   *   {@link https://cloud.opendesign.com/docs//pages/server/api.html#Assemblies | Open Cloud Assemblies API}.
   */
  override delete(): Promise<any> {
    return super.delete("").then((response) => response.json());
  }

  /**
   * Saves assembly properties changes to the server. Call this method to update assembly data on the
   * server after any property changes.
   */
  save(): Promise<this> {
    return this.update(this.data);
  }

  // Reserved for future use

  setPreview(image?: BodyInit | null): Promise<this> {
    console.warn("Assembly does not support preview");
    return Promise.resolve(this);
  }

  deletePreview(): Promise<this> {
    console.warn("Assembly does not support preview");
    return Promise.resolve(this);
  }

  /**
   * Returns list of assembly models.
   */
  getModels(): Promise<Model[]> {
    return this.get("/geometry")
      .then((response) => response.json())
      .then((array) => array.map((data: any) => new Model(data, this)));
  }

  /**
   * Returns a model transformation.
   *
   * @param handle - Model original handle.
   */
  getModelTransformMatrix(handle: string): IModelTransformMatrix {
    return this.data.transform[handle];
  }

  /**
   * Sets or removes a model transformation.
   *
   * @param handle - Model original handle.
   * @param transform - Transformation matrix. Specify `undefined` to remove transformation.
   */
  setModelTransformMatrix(handle: string, transform?: IModelTransformMatrix): Promise<this> {
    const obj = { ...this.data.transform };
    obj[handle] = transform;
    return this.update({ transform: obj });
  }

  /**
   * Object properties.
   *
   * @typedef {any} Properties
   * @property {string} handle - Object original handle.
   * @property {string | any} * - Object property. Can be `any` for nested properties.
   */

  /**
   * Returns the properties for an objects in the assembly.
   *
   * @param handles - Object original handle or handles array. Specify `undefined` to get properties for
   *   all objects in the assembly.
   */
  getProperties(handles?: string | string[]): Promise<any[]> {
    const relativePath = handles !== undefined ? `/properties?handles=${handles}` : "/properties";
    return this.get(relativePath).then((response) => response.json());
  }

  /**
   * Returns the list of original handles for an objects in the file that match the specified patterns.
   * Search patterns may be combined using query operators.
   *
   * @example Simple search pattern.
   *
   * ```javascript
   * searchPattern = {
   *   key: "Category",
   *   value: "OST_Stairs",
   * };
   * ```
   *
   * @example Search patterns combination.
   *
   * ```javascript
   * searchPattern = {
   *   $or: [
   *     {
   *       $and: [
   *         { key: "Category", value: "OST_GenericModel" },
   *         { key: "Level", value: "03 - Floor" },
   *       ],
   *     },
   *     { key: "Category", value: "OST_Stairs" },
   *   ],
   * };
   * ```
   *
   * @param searchPattern - Search pattern or combination of the patterns, see example below.
   */
  searchProperties(searchPattern: any): Promise<any[]> {
    return this.post("/properties/search", searchPattern).then((response) => response.json());
  }

  /**
   * Returns the CDA tree for an assembly.
   */
  getCdaTree(): Promise<ICdaNode[]> {
    return this.get(`/properties/tree`).then((response) => response.json());
  }

  /**
   * Returns a list of assembly viewpoints. For more information, see
   * {@link https://cloud.opendesign.com/docs//pages/server/api.html#AssemblyViewpoints | Open Cloud Assembly Viewpoints API}.
   */
  getViewpoints(): Promise<any[]> {
    return this.get("/viewpoints")
      .then((response) => response.json())
      .then((viewpoints) => viewpoints.result);
  }

  /**
   * Saves a new assembly viewpoint to the server. To create a viewpoint use `Viewer.createViewpoint()`.
   *
   * @param viewpoint - Viewpoint object. For more information, see
   *   {@link https://cloud.opendesign.com/docs//pages/server/api.html#AssemblyViewpoints | Open Cloud Assembly Viewpoints API}.
   */
  saveViewpoint(viewpoint: any): Promise<any> {
    return this.post("/viewpoints", viewpoint).then((response) => response.json());
  }

  /**
   * Deletes the specified assembly viewpoint.
   *
   * @param guid - Viewpoint GUID.
   * @returns Returns a deleted viewpoint. For more information, see
   *   {@link https://cloud.opendesign.com/docs//pages/server/api.html#AssemblyViewpoints | Open Cloud Assembly Viewpoints API}.
   */
  deleteViewpoint(guid: string): Promise<any> {
    return super.delete(`/viewpoints/${guid}`).then((response) => response.json());
  }

  /**
   * Returns the viewpoint snapshot as base64-encoded
   * {@link https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs | Data URL}.
   *
   * @param guid - Viewpoint GUID.
   */
  getSnapshot(guid: string): Promise<string> {
    return this.get(`/viewpoints/${guid}/snapshot`).then((response) => response.text());
  }

  /**
   * Returns the viewpoint snapshot data.
   *
   * @param guid - Viewpoint GUID.
   * @param bitmapGuid - Bitmap GUID.
   */
  getSnapshotData(guid: string, bitmapGuid: string): Promise<string> {
    return this.get(`/viewpoints/${guid}/bitmaps/${bitmapGuid}`).then((response) => response.text());
  }

  /**
   * Downloads an assembly resource file. Resource files are files that contain model scene descriptions,
   * or geometry data.
   *
   * @param dataId - Resource file name.
   * @param onProgress - Download progress callback.
   * @param signal - An
   *   {@link https://developer.mozilla.org/docs/Web/API/AbortController | AbortController} signal. Allows
   *   to communicate with a fetch request and abort it if desired.
   */
  downloadResource(
    dataId: string,
    onProgress?: (progress: number, chunk: Uint8Array) => void,
    signal?: AbortSignal
  ): Promise<ArrayBuffer> {
    return this.httpClient
      .downloadFile(this.getEndpointPath(`/downloads/${dataId}`), onProgress, { signal, headers: this.headers })
      .then((response) => response.arrayBuffer());
  }

  /**
   * Downloads a part of assembly resource file. Resource files are files that contain model scene
   * descriptions, or geometry data.
   *
   * @param dataId - Resource file name.
   * @param ranges - A range of resource file contents to download.
   * @param requestId - Request ID for download progress callback.
   * @param onProgress - Download progress callback.
   * @param signal - An
   *   {@link https://developer.mozilla.org/docs/Web/API/AbortController | AbortController} signal. Allows
   *   to communicate with a fetch request and abort it if desired.
   */
  downloadResourceRange(
    dataId: string,
    requestId: number,
    ranges: Array<{ begin: number; end: number; requestId: number }>,
    onProgress?: (progress: number, chunk: Uint8Array, requestId: number) => void,
    signal?: AbortSignal
  ): Promise<ArrayBuffer> {
    return this.httpClient
      .downloadFileRange(
        this.getEndpointPath(`/downloads/${dataId}?requestId=${requestId}`),
        requestId,
        ranges,
        onProgress,
        { signal, headers: this.headers }
      )
      .then((response) => response.arrayBuffer());
  }

  /**
   * Deprecated since `25.3`. Use {@link downloadResource | downloadResource()} instead.
   *
   * @deprecated
   */
  partialDownloadResource(
    dataId: string,
    onProgress?: (progress: number, chunk: Uint8Array) => void,
    signal?: AbortSignal
  ): Promise<ArrayBuffer> {
    console.warn(
      "Assembly.partialDownloadResource() has been deprecated since 25.3 and will be removed in a future release, use Assembly.downloadResource() instead."
    );
    return this.downloadResource(dataId, onProgress, signal);
  }

  /**
   * Deprecated since `25.3`. Use {@link downloadResourceRange | downloadResourceRange()} instead.
   */
  async downloadFileRange(
    requestId: number,
    records: any | null,
    dataId: string,
    onProgress?: (progress: number, chunk: Uint8Array, requestId: number) => void,
    signal?: AbortSignal
  ): Promise<void> {
    await this.downloadResourceRange(dataId, requestId, records, onProgress, signal);
  }

  /**
   * Returns a list of assembly references containing references from all the files from which the
   * assembly was created.
   *
   * References are images, fonts, or any other files to correct rendering of the assembly.
   *
   * @param signal - An
   *   {@link https://developer.mozilla.org/docs/Web/API/AbortController | AbortController} signal, which
   *   can be used to abort waiting as desired.
   */
  async getReferences(signal?: AbortSignal): Promise<IFileReferences> {
    const files = new Endpoint("/files", this.httpClient, this.headers);
    const references = await Promise.all(
      this.associatedFiles
        .map((file) => `/${file.fileId}/references`)
        .map((link) => files.get(link, signal).then((response) => response.json()))
    )
      .then((references) => references.map((x) => x.references))
      .then((references) => references.reduce((x, v) => [...v, ...x], []))
      .then((references) => [...new Set(references.map(JSON.stringify))].map((x: string) => JSON.parse(x)));
    return { id: "", references };
  }

  /**
   * Waits for assembly to be created. Assembly is created when it changes to `done` or `failed` status.
   *
   * @param params - An object containing waiting parameters.
   * @param params.timeout - The time, in milliseconds that the function should wait assembly. If
   *   assembly is not created during this time, the `TimeoutError` exception will be thrown.
   * @param params.interval - The time, in milliseconds, the function should delay in between checking
   *   assembly status.
   * @param params.signal - An
   *   {@link https://developer.mozilla.org/docs/Web/API/AbortController | AbortController} signal, which
   *   can be used to abort waiting as desired.
   * @param params.onCheckout - Waiting progress callback. Return `true` to cancel waiting.
   */
  waitForDone(params?: {
    timeout?: number;
    interval?: number;
    signal?: AbortSignal;
    onCheckout?: (assembly: Assembly, ready: boolean) => boolean;
  }): Promise<this> {
    const checkDone = () =>
      this.checkout().then((assembly) => {
        const ready = ["done", "failed"].includes(assembly.status);
        const cancel = params?.onCheckout?.(assembly, ready);
        return cancel || ready;
      });

    return waitFor(checkDone, params).then(() => this);
  }

  /**
   * Returns a list of assembly clash tests.
   *
   * @param start - The starting index in the test list. Used for paging.
   * @param limit - The maximum number of tests that should be returned per request. Used for paging.
   * @param name - Filter the tests by part of the name. Case sensitive.
   * @param ids - List of tests IDs to return.
   * @param sortByDesc - Allows to specify the descending order of the result. By default tests are
   *   sorted by name in ascending order.
   * @param sortField - Allows to specify sort field.
   */
  getClashTests(
    start?: number,
    limit?: number,
    name?: string,
    ids?: string | string[],
    sortByDesc?: boolean,
    sortField?: string
  ): Promise<{ allSize: number; start: number; limit: number; result: ClashTest[]; size: number }> {
    const searchParams = new URLSearchParams();
    if (start > 0) searchParams.set("start", start.toString());
    if (limit > 0) searchParams.set("limit", limit.toString());
    if (name) searchParams.set("name", name);
    if (ids) {
      if (Array.isArray(ids)) ids = ids.join("|");
      if (typeof ids === "string") ids = ids.trim();
      if (ids) searchParams.set("id", ids);
    }
    if (sortByDesc !== undefined) searchParams.set("sortBy", sortByDesc ? "desc" : "asc");
    if (sortField) searchParams.set("sortField", sortField);

    let queryString = searchParams.toString();
    if (queryString) queryString = "?" + queryString;

    return this.get(`/clashes${queryString}`)
      .then((response) => response.json())
      .then((tests) => {
        return {
          ...tests,
          result: tests.result.map((data) => new ClashTest(data, this.path, this.httpClient)),
        };
      });
  }

  /**
   * Returns information about the specified assembly clash test.
   *
   * @param testId - Test ID.
   */
  getClashTest(testId: string): Promise<ClashTest> {
    return this.get(`/clashes/${testId}`)
      .then((response) => response.json())
      .then((data) => new ClashTest(data, this.path, this.httpClient));
  }

  /**
   * Creates an assembly clash test. Assembly must be in a `done` state, otherwise the test will fail.
   *
   * @param name - Test name.
   * @param selectionTypeA - The type of first selection set for clash detection. Can be one of:
   *
   *   - `all` - All file/assembly objects.
   *   - `handle` - Objects with original handles specified in the `selectionSetA`.
   *   - `models` - All objects of the models with original handles specified in the `selectionSetA`.
   *   - `searchquery` - Objects retrieved by the search queries specified in `selectionSetA`.
   *
   * @param selectionTypeB - The type of second selection set for clash detection. Can be one of:
   *
   *   - `all` - All file/assembly objects.
   *   - `handle` - Objects with original handles specified in the `selectionSetB`.
   *   - `models` - All objects of the models with original handles specified in the `selectionSetB`.
   *   - `searchquery` - Objects retrieved by the search queries specified in `selectionSetB`.
   *
   * @param selectionSetA - First selection set for clash detection. Objects from `selectionSetA` will be
   *   tested against each others by objects from the `selectionSetB` during the test.
   * @param selectionSetB - Second selection set for clash detection. Objects from `selectionSetB` will
   *   be tested against each others by objects from the `selectionSetA` during the test.
   * @param params - An object containing test parameters.
   * @param params.tolerance - The distance of separation between objects at which test begins detecting
   *   clashes.
   * @param params.clearance - The type of the clashes that the test detects:
   *
   *   - `true` - Сlearance clash. A clash in which the object A may or may not intersect with object B, but
   *       comes within a distance of less than the `tolerance`.
   *   - `false` - Hard clash. A clash in which the object A intersects with object B by a distance of more
   *       than the `tolerance`.
   *
   * @param params.waitForDone - Wait for test to complete.
   * @param params.timeout - The time, in milliseconds that the function should wait test. If test is not
   *   complete during this time, the `TimeoutError` exception will be thrown.
   * @param params.interval - The time, in milliseconds, the function should delay in between checking
   *   test status.
   * @param params.signal - An
   *   {@link https://developer.mozilla.org/docs/Web/API/AbortController | AbortController} signal, which
   *   can be used to abort waiting as desired.
   */
  createClashTest(
    name: string,
    selectionTypeA: string,
    selectionTypeB: string,
    selectionSetA?: string | string[],
    selectionSetB?: string | string[],
    params?: {
      tolerance?: number | string;
      clearance?: boolean;
      waitForDone?: boolean;
      timeout?: number;
      interval?: number;
      signal?: AbortSignal;
    }
  ): Promise<ClashTest> {
    const { tolerance, clearance, waitForDone } = params ?? {};
    if (!Array.isArray(selectionSetA)) selectionSetA = [selectionSetA];
    if (!Array.isArray(selectionSetB)) selectionSetB = [selectionSetB];

    return this.post("/clashes", {
      name,
      selectionTypeA,
      selectionTypeB,
      selectionSetA,
      selectionSetB,
      tolerance,
      clearance,
    })
      .then((response) => response.json())
      .then((data) => new ClashTest(data, this.path, this.httpClient))
      .then((result) => (waitForDone ? result.waitForDone(params) : result));
  }

  /**
   * Deletes the specified assembly clash test.
   *
   * @param testId - Test ID.
   * @returns Returns the raw data of a deleted test. For more information, see
   *   {@link https://cloud.opendesign.com/docs//pages/server/api.html#Assemblies | Open Cloud Assemblies API}.
   */
  deleteClashTest(testId: string): Promise<any> {
    return super.delete(`/clashes/${testId}`).then((response) => response.json());
  }

  // Reserved for future use

  updateVersion(
    files?: string[],
    params: {
      waitForDone?: boolean;
      timeout?: number;
      interval?: number;
      signal?: AbortSignal;
      onProgress?: (progress: number, file: globalThis.File) => void;
    } = {
      waitForDone: false,
    }
  ): Promise<Assembly> {
    return Promise.reject(new Error("Assembly version support will be implemeted in a future release"));
  }

  getVersions(): Promise<Assembly[] | undefined> {
    return Promise.resolve(undefined);
  }

  getVersion(version: number): Promise<Assembly> {
    return Promise.reject(new FetchError(404));
  }

  deleteVersion(version: number): Promise<any> {
    return Promise.reject(new FetchError(404));
  }

  setActiveVersion(version: number): Promise<this> {
    return this.update({ activeVersion: version });
  }

  // Reserved for future use

  createSharedLink(permissions?: ISharedLinkPermissions): Promise<SharedLink> {
    return Promise.reject(new Error("Assembly shared link will be implemeted in a future release"));
  }

  getSharedLink(): Promise<SharedLink> {
    return Promise.resolve(undefined);
  }

  deleteSharedLink(): Promise<any> {
    return Promise.reject(new FetchError(404));
  }
}
