import { spawn } from "threads";
import ProofmodeWorker from './proofmodeWorker?worker'

export type ProofCheckResult = {
          name?: string;
        json?: string;
        integrity?: { pgp?: any; c2pa?: any; exif?: any; opentimestamps?: any };
};

class ProofMode {
  worker: any | undefined = undefined;

  async getProofcheckWorker() {
    if (this.worker) {
      return this.worker;
    }
    try {
      this.worker = await spawn(new ProofmodeWorker(), { timeout: 20000 });
      this.worker.values().subscribe(({ type, message }: { type: string, message: string}) => {
        console.log("ProofCheck:", type, message);
      });
    } catch (error) {}
    return this.worker;
  }

  async proofCheckFile(file: File): Promise<ProofCheckResult | undefined> {
    try {
      const worker = await this.getProofcheckWorker();
      const res = await worker.checkFiles([file]);
      if (res && res.files && res.files.length == 1) {
        delete res.files[0].data; // Don't need to hang on to the data!
        return res.files[0];
      }
    } catch (error) {
    }
    return undefined;
  }

  async proofCheckSource(src: string): Promise<ProofCheckResult | undefined> {
    try {
      const worker = await this.getProofcheckWorker();
      const res = await worker.checkURLs([src]);
      if (res && res.files && res.files.length == 1) {
        delete res.files[0].data; // Don't need to hang on to the data!
        return res.files[0];
      }
    } catch (error) {
    }
    return undefined;
  }
}


export default new ProofMode();