// miner/src/js/mine-worker.js

export default class MineWorker {
  constructor() {
    // Initialize the worker pointing to the public file
    this.worker = new Worker('/miner.worker.js');
    
    // Internal stats that miner.js reads
    this.hashesPerSecond = 0;
    this.hashesTotal = 0;
    this.isJobSet = false;

    // Listen for messages from miner.worker.js
    this.worker.onmessage = (event) => {
      const data = event.data;

      if (data.type === 'hash-stats') {
        this.hashesPerSecond = data.payload.hashesPerSecond;
        this.hashesTotal += data.payload.hashes;
      }
      else if (data.type === 'hash-found') {
        this.hashesPerSecond = data.payload.hashesPerSecond;
        this.hashesTotal += data.payload.hashes;
        if (this.onTargetMetCallback) {
            this.onTargetMetCallback(data.payload);
        }
      }
      else if (data === 'worker-initialized' || data.type === 'miner-initialized' || data.type === 'emscripten-initialized') {
        console.log("MainThread: Worker initialized");
      }
    };

    this.worker.onerror = (e) => {
      console.error("MainThread: Worker Error", e);
    };
  }

  setJob(job, callback) {
    this.onTargetMetCallback = callback;
    this.isJobSet = true;
    // Send the job to the worker
    this.worker.postMessage({
      type: 'set-job',
      payload: {
        job: job,
        throttle: job.throttle
      }
    });
  }

  stop() {
    if (this.worker) {
      this.worker.terminate();
      this.worker = null;
    }
    this.hashesPerSecond = 0;
  }
}
