// @ts-ignore
import * as _qjsOsImp from "os";
// @ts-ignore
import * as _qjsStdImp from "std";

export interface QjsHttpResp {
  status: number;
  data: ArrayBuffer;
  headers?: string[];
}

export interface QjsHttpOptions {
  method: string;
  debug?: boolean;
  data?: ArrayBuffer;
  headers?: string[];
}

export interface ErrReceiver {
  errno?: number;
}

/**
 * File handle. Thin wrapper around a libc FILE object.
 */
export interface QjsFile {
  /**
   * Close the file. Return 0 if OK or -errno in case of I/O error.
   */
  close(): number;

  /**
   * Outputs the string with UTF-8 encoding.
   */
  puts(str: string): void;

  /**
   * Read max_size bytes from the file and return them as a string
   * assuming UTF-8 encoding.
   *
   * If max_size is not present, the file is read up its end.
   */
  readAsString(max_size?: number): string;
}

export interface QjsOsLib {
  fetchHttp(
    url: string,
    options?: QjsHttpOptions,
  ): {
    promise: Promise<QjsHttpResp>;
    cancelFn: () => number;
  };
  postMessageToHost(s: string): void;
  setMessageFromHostHandler(h: (s: string) => void): void;
  rename(oldPath: string, newPath: string): number;
  remove(path: string): number;

  readonly O_RDONLY: number;
  readonly O_WRONLY: number;
  readonly O_RDWR: number;
  readonly O_APPEND: number;
  readonly O_CREAT: number;
  readonly O_EXCL: number;
  readonly O_TRUNC: number;
}

export interface QjsStdLib {
  writeFile(filename: string, contents: string): void;
  loadFile(filename: string): string;
  open(filename: string, mode: string, errorObj?: ErrReceiver): QjsFile | null;
}

// This is not the nodejs "os" module, but the qjs "os" module.
export const qjsOs: QjsOsLib = _qjsOsImp as any;

export const qjsStd: QjsStdLib = _qjsStdImp as any;
