///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2002-2026, 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-2026 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 { IClashItem } from "./IAssembly";
import { IShortUserDesc } from "./IUser";
import { waitFor, userFullName, userInitials } from "./Utils";

/**
 * Provides properties and methods for obtaining information about a file/assembly clash detection test.
 */
export class ClashTest extends Endpoint {
  private _data: any;

  /**
   * @param data - Raw test 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 path - The clash test API path of the file/assembly that owns the test.
   * @param httpClient - HTTP client instance used to send requests to the REST API server.
   */
  constructor(data: any, path: string, httpClient: IHttpClient) {
    super(`${path}/clashes/${data.id}`, httpClient);
    this.data = data;
  }

  /**
   * The type of the clashes that the test detects:
   *
   * - `true` - Clearance 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 {@link tolerance}.
   * - `false` - Hard clash. A clash in which the object A intersects with object B by a distance of more
   *   than the {@link tolerance}.
   *
   * @readonly
   */
  get clearance(): boolean {
    return this.data.clearance;
  }

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

  /**
   * Raw test data received from the server. For more information, see
   * {@link https://cloud.opendesign.com/docs//pages/server/api.html#Assemblies | Open Cloud Assemblies API}.
   *
   * @readonly
   */
  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);
  }

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

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

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

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

  /**
   * Test owner (the user who created the test).
   *
   * @readonly
   */
  get owner(): IShortUserDesc {
    return this.data.owner;
  }

  /**
   * First selection set for clash detection. Objects from `selectionSetA` will be tested against each
   * others by objects from the `selectionSetB` during the test.
   *
   * @readonly
   */
  get selectionSetA(): string[] {
    return this.data.selectionSetA;
  }

  /**
   * 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`.
   *
   * @readonly
   */
  get selectionTypeA(): string {
    return this.data.selectionTypeA;
  }

  /**
   * Second selection set for clash detection. Objects from `selectionSetB` will be tested against each
   * others by objects from the `selectionSetA` during the test.
   *
   * @readonly
   */
  get selectionSetB(): string[] {
    return this.data.selectionSetB;
  }

  /**
   * 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`.
   *
   * @readonly
   */
  get selectionTypeB(): string {
    return this.data.selectionTypeB;
  }

  /**
   * Test status. Can be `none`, `waiting`, `inprogress`, `done`, or `failed`.
   *
   * @readonly
   */
  get status(): string {
    return this.data.status;
  }

  /**
   * The distance of separation between objects at which test begins detecting clashes.
   *
   * @readonly
   */
  get tolerance(): number {
    return this.data.tolerance;
  }

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

  /**
   * Updates test data on the server.
   *
   * @param data - Raw test 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 a test and its results report from the server.
   *
   * @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}.
   */
  override delete(): Promise<any> {
    return super.delete("").then((response) => response.json());
  }

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

  /**
   * Waits for test to complete. Test is done 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 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.
   * @param params.onCheckout - Waiting progress callback. Return `true` to cancel waiting.
   */
  waitForDone(params?: {
    timeout?: number;
    interval?: number;
    signal?: AbortSignal;
    onCheckout?: (test: ClashTest, ready: boolean) => boolean;
  }): Promise<this> {
    const checkDone = () =>
      this.checkout().then((test) => {
        const ready = ["done", "failed"].includes(test.status);
        const cancel = params?.onCheckout?.(test, ready);
        return cancel || ready;
      });
    return waitFor(checkDone, params).then(() => this);
  }

  /**
   * Returns a list of detected clashes for this test.
   */
  getReport(): Promise<IClashItem[]> {
    return this.get("/report").then((response) => response.json());
  }
}
