///////////////////////////////////////////////////////////////////////////////
// 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 { waitFor } from "./Utils";

/**
 * Provides properties and methods for obtaining information about a job on the Open Cloud Server.
 */
export class Job extends Endpoint {
  private _data: any;

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

  /**
   * The ID of the assembly the job is working on (internal).
   *
   * @readonly
   */
  get assemblyId(): string {
    return this.data.assemblyId;
  }

  /**
   * Job owner ID (the user who created the job). Use {@link Client.getUser | Client.getUser()} to obtain
   * detailed user information.
   *
   * @readonly
   */
  get authorId(): string {
    return this.data.authorId;
  }

  /**
   * Job 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 job data received from the server. For more information, see
   * {@link https://cloud.opendesign.com/docs//pages/server/api.html#Jobs | Open Cloud Jobs API}.
   *
   * @readonly
   */
  get data(): any {
    return this._data;
  }

  private set data(value: any) {
    this._data = value;
  }

  /**
   * `true` if job is `done` or `failed`. See {@link status} for more details.
   *
   * @readonly
   */
  get done(): boolean {
    return this.data.status === "done" || this.data.status === "failed";
  }

  /**
   * The ID of the file the job is working on.
   *
   * @readonly
   */
  get fileId(): string {
    return this.data.fileId;
  }

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

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

  /**
   * Job type. Can be one of:
   *
   * - `geometry` - Convert file geometry data to `VSFX` format.
   * - `geometryGltf` - Convert file geometry data to `glTF` format.
   * - `properties` - Extract file properties.
   * - `validation` - Validate the IFC file.
   * - `clash` - Create the clash detection report.
   * - `dwg`, `obj`, `gltf`, `glb`, `vsf`, `pdf`, `3dpdf` - Export file to the specified format.
   * - Other custom job name.
   *
   * @readonly
   */
  get outputFormat(): string {
    return this.data.outputFormat;
  }

  /**
   * Parameters with which the job was started. For more information, see
   * {@link https://cloud.opendesign.com/docs//pages/server/api.html#Jobs | Open Cloud Jobs API}.
   *
   * @readonly
   */
  get parameters(): any {
    return this.data.parameters;
  }

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

  /**
   * Job status description message.
   *
   * @readonly
   */
  get statusMessage(): string {
    return this.data.statusMessage;
  }

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

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

  /**
   * Updates job data on the server.
   *
   * Only administrators can update job data. If the current logged in user is not an administrator, an
   * exception will be thrown.
   *
   * @param data - Raw job data. For more information, see
   *   {@link https://cloud.opendesign.com/docs//pages/server/api.html#Jobs | Open Cloud Jobs API}.
   */
  async update(data: any): Promise<this> {
    const response = await this.put("", data);
    this.data = await response.json();
    return this;
  }

  /**
   * Deletes a job from the server.
   *
   * You cannot delete other users' jobs unless you are an administrator.
   *
   * You can only delete jobs that are in the `waiting` status (jobs that have been created but not yet
   * started). Jobs that are currently running (`inprogress`) or have already completed (`done` or
   * `failed`) cannot be deleted.
   *
   * @returns Returns the raw data of a deleted job. For more information, see
   *   {@link https://cloud.opendesign.com/docs//pages/server/api.html#Jobs | Open Cloud Jobs API}.
   */
  override delete(): Promise<any> {
    return super.delete("").then((response) => response.json());
  }

  // /**
  //  * Save job properties changes to the server. Call this method to update job data on the server
  //  * after any property changes.
  //  */
  // save() {
  //   return this.update(this.data);
  // }

  /**
   * Waits for job to be done. Job 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 for the job. If the
   *   job is not done during this time, the `TimeoutError` exception will be thrown.
   * @param params.interval - The time, in milliseconds, the function should delay in between checking
   *   job 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?: (job: Job, ready: boolean) => boolean;
  }): Promise<this> {
    const checkDone = () =>
      this.checkout().then((job) => {
        const ready = ["done", "failed"].includes(job.status);
        const cancel = params?.onCheckout?.(job, ready);
        return cancel || ready;
      });

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