///////////////////////////////////////////////////////////////////////////////
// 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.
///////////////////////////////////////////////////////////////////////////////

export class FileLoader {
  private requestHeader: HeadersInit;
  private withCredentials: boolean;
  private abortSignal: AbortSignal;

  constructor() {
    this.requestHeader = {};
    this.withCredentials = false;
    this.abortSignal = undefined;
  }

  setRequestHeader(requestHeader: HeadersInit) {
    this.requestHeader = requestHeader;
  }

  setWithCredentials(withCredentials: boolean) {
    this.withCredentials = withCredentials;
  }

  setAbortSignal(abortSignal: AbortSignal) {
    this.abortSignal = abortSignal;
  }

  load(file: any, onProgress?: (event) => void): Promise<ArrayBuffer> {
    if (typeof file === "string") {
      const request = new Request(file, {
        headers: new Headers(this.requestHeader),
        credentials: this.withCredentials ? "include" : "same-origin",
        signal: this.abortSignal,
      });

      return fetch(request)
        .then((response) => {
          if (!response.ok) throw new Error(`Failed to fetch "${response.url}", status ${response.status}`);

          const contentLength = response.headers.get("X-File-Size") || response.headers.get("Content-Length");
          const total = parseInt(contentLength || "", 10) || 0;
          const lengthComputable = total > 0;

          const stream = new ReadableStream({
            async start(controller) {
              const reader = response.body.getReader();
              let loaded = 0;
              try {
                while (true) {
                  const { done, value } = await reader.read();
                  if (done) break;
                  if (onProgress) {
                    loaded += value.byteLength;
                    onProgress(new ProgressEvent("progress", { lengthComputable, loaded, total }));
                  }
                  controller.enqueue(value);
                }
                controller.close();
              } catch (e) {
                controller.error(e);
              }
            },
          });

          return new Response(stream);
        })
        .then((response) => response.arrayBuffer());
    }

    if (file instanceof globalThis.File) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result as any);
        reader.onerror = () => reject(reader.error);
        reader.onprogress = onProgress;
        reader.readAsArrayBuffer(new Blob([file]));
      });
    }

    if (onProgress) {
      const total = (file as ArrayBuffer).byteLength;
      const lengthComputable = total > 0;
      const loaded = total;
      onProgress(new ProgressEvent("progress", { lengthComputable, loaded, total }));
    }

    return Promise.resolve(file);
  }
}
