/// <reference path="./shims.d.ts" />

import { Viewer2D } from './Viewer2D.js';
import { parseDwgBuffer, type CadParseResult } from './dwgParser';
import { is2D, isDwg } from './ext2d';
import { parseDxfBuffer } from './parseDxf';
import { setDefaultFontUrl } from './slugText';

export type CadInput = {
  name: string;
  data: ArrayBuffer | Uint8Array;
};

export type CadLoadSummary = {
  entityCount: number;
};

export type Viewer2DOptions = {
  fontUrl?: string;
};

function toArrayBuffer(data: ArrayBuffer | Uint8Array): ArrayBuffer {
  if (data instanceof ArrayBuffer) return data;
  return data.slice().buffer as ArrayBuffer;
}

export function isCad2DFile(name: string): boolean {
  return is2D(name);
}

async function parseCad(input: CadInput): Promise<CadParseResult> {
  const buffer = toArrayBuffer(input.data);
  if (isDwg(input.name)) return parseDwgBuffer(new Uint8Array(buffer));
  if (is2D(input.name)) return parseDxfBuffer(buffer);

  const head = new TextDecoder('latin1').decode(
    new Uint8Array(buffer, 0, Math.min(6, buffer.byteLength)),
  );
  if (head.startsWith('AC')) return parseDwgBuffer(new Uint8Array(buffer));
  return parseDxfBuffer(buffer);
}

export async function loadCad(
  viewer: Pick<Viewer2D, 'load' | 'resize'>,
  input: CadInput,
): Promise<CadLoadSummary> {
  const result = await parseCad(input);
  viewer.load(result);
  viewer.resize();
  return { entityCount: result.entities?.length ?? 0 };
}

export function createViewer2D(container: HTMLElement, options: Viewer2DOptions = {}): Viewer2D {
  if (options.fontUrl) setDefaultFontUrl(options.fontUrl);
  return new Viewer2D(container);
}
