import fs from "node:fs";
import exec from "node:child_process";
import _ from "underscore";
import PCMPlayer from 'pcm-player'
import pcm from "pcm";

var min = 1.0;
var max = -1.0;
const pcmData = []
await pcm.getPcmData('/home/boazsender/Downloads/BlackPortal recording April 6 2025.wav', { stereo: true, sampleRate: 44100 },
  function(sample, channel) {
    // Sample is from [-1.0...1.0], channel is 0 for left and 1 for right
    pcmData.push(sample)
    min = Math.min(min, sample);
    max = Math.max(max, sample);
  },
  function(err, output) {
    if (err)
      throw new Error(err);
    console.log('min=' + min + ', max=' + max);
  }
);

console.log(pcmData)


/**
 * [findPeaks Naive algo to identify peaks in the audio data, and wave]
 * @param  {[type]} pcmdata    [description]
 * @param  {[type]} samplerate [description]
 * @return {[type]}            [description]
 */
function findPeaks(pcmdata, samplerate) {
  const interval = 0.05 * 1000;
  index = 0;
  const step = Math.round(samplerate * (interval / 1000));
  const max = 0;
  const prevmax = 0;
  const prevdiffthreshold = 0.3;

  //loop through song in time with sample rate
  const samplesound = setInterval(
    function () {
      if (index >= pcmdata.length) {
        clearInterval(samplesound);
        console.log("finished sampling sound");
        return;
      }

      for (const i = index; i < index + step; i++) {
        max = pcmdata[i] > max ? pcmdata[i].toFixed(1) : max;
      }

      // Spot a significant increase? Potential peak
      bars = getbars(max);
      if (max - prevmax >= prevdiffthreshold) {
        bars = bars + " == peak == ";
      }

      // Print out mini equalizer on commandline
      console.log(bars, max);
      prevmax = max;
      max = 0;
      index += step;
    },
    interval,
    pcmdata
  );
}

/**
 * TBD
 * @return {[type]} [description]
 */
function detectBeats() {}

/**
 * [getbars Visualize image sound using bars, from average pcmdata within a sample interval]
 * @param  {[Number]} val [the pcmdata point to be visualized ]
 * @return {[string]}     [a set of bars as string]
 */
function getbars(val) {
  bars = "";
  for (const i = 0; i < val * 50 + 2; i++) {
    bars = bars + "|";
  }
  return bars;
}

/**
 * [Plays a sound file]
 * @param  {[string]} soundfile [file to be played]
 * @return {[type]}           [void]
 */
function playsound(soundfile) {
  // linux or raspi
  // const create_audio = exec('aplay'+soundfile, {maxBuffer: 1024 * 500}, function (error, stdout, stderr) {
  const create_audio = exec(
    "mplayer -loop 0 " + soundfile,
    { maxBuffer: 1024 * 500 },
    function (error, stdout, stderr) {
      if (error !== null) {
        console.log("exec error: " + error);
      } else {
        //console.log(" finshed ");
        //micInstance.resume();
      }
    }
  );
}

