navigator.getUserMedia = (navigator.getUserMedia ||
  navigator.webkitGetUserMedia ||
  navigator.mozGetUserMedia ||
  navigator.msGetUserMedia);

// set up basic variables for app
var clipName = "";
var cName = "";
var seconds = 0, minutes = 0, hours = 0;
var cTime = '00:00';
var timer;
var audio;
var counter = 0;
var record = document.querySelector('.record');
var stop = document.querySelector('.stop');
var soundClips = document.querySelector('.sound-clips');
var canvas = document.querySelector('.visualizer');
var MAX_RECORD_TIME = 120;
// disable stop button while not recording
var start_stop=false
// stop.disabled = true;
record.disabled = false;
record.style.width="400px"
// visualiser setup - create web audio api context and canvas

var audioCtx = new (window.AudioContext || webkitAudioContext)();
var canvasCtx = canvas.getContext("2d");

$("#dialog").dialog({
  autoOpen: false,
  width: 190,
  draggable: false,
  buttons: [
    {
      text: "Ok",
      click: function () {
        $(this).dialog("close");
        onClose();
      }
    }
  ],

  position: {
    at: "top",
  }
});

$(".ui-dialog-titlebar-close").click(function () {
  clipArr.pop()
  //counter--;
})

var clipArr = []

function onClose() {
  clipName = $("#inp").val();

  var clipContainer = document.createElement('article');
  clipLabel = document.createElement('p');

  clipContainer.classList.add('clip');

  var deleteButton = document.createElement('button');
  deleteButton.textContent = 'Delete';
  deleteButton.className = 'delete';
  deleteButton.setAttribute("id", "del_" + current_ID);

  if (clipName == "") {
    clipArr.push('Clip ' + (clipArr.length + 1))
    clipLabel.textContent = 'Clip ' + current_ID;
  } else {
    clipLabel.textContent = clipName;
  }

  clipContainer.appendChild(audio);
  clipContainer.appendChild(clipLabel);
  clipContainer.appendChild(deleteButton);
  soundClips.appendChild(clipContainer);

  var cc = navigator.userAgent.indexOf("Chrome") > -1;
  //console.log(cc," -------------");

  // if (cc) {
  //   customTimer(clipContainer, audio);
  // }

  deleteButton.onclick = function (e) {
    deleteBtnId = parseInt(e.target.id.replace("del_", ""));
    console.log("THIS: ", "Clip " + deleteBtnId);
    clipArr.splice(clipArr.indexOf("Clip " + deleteBtnId), 1)
    console.log(clipArr, "ondelete clicked ")
    evtTgt = e.target;
    evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
  }

  clipLabel.onclick = function (e) {
    var existingName = clipLabel.textContent;
    var newClipName = prompt('Enter a new name for your sound clip?', existingName);
    if (newClipName === null || !newClipName.length) {
      clipLabel.textContent = existingName;
    } else {
      clipLabel.textContent = newClipName;
    }
  }

}


function getChromeVersion() {
  var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
  return raw ? parseInt(raw[2], 10) : false;
}


console.log(navigator.userAgent, " -------------");
//main block for doing the audio recording


var constraints = { audio: true };
var chunks = [];


navigator.mediaDevices.getUserMedia(constraints)

  .then(function (stream) {

    var mediaRecorder = new MediaRecorder(stream);




    visualize(stream);

    
    record.onclick = function () {
      console.log();
      
      if(start_stop===false){
        console.log("Audio recording");
        mediaRecorder.start();
        record.style.background = "red";
        record.innerHTML = "Stop recording";
        start_stop=true;
        timer = setInterval(updateTiming, 1000);
      }else{
        console.log("stop recording");
        mediaRecorder.stop();
        record.style.background = "";
        record.style.color = "";
        record.innerHTML = "Record";
      start_stop=false;
      }
      
    }

    
    
    
    




    // stop.onclick = function () {
    //   mediaRecorder.stop();
    //   //console.log(mediaRecorder.state);
    //   //console.log("3 recorder stopped ", mediaRecorder.state);
    //   record.style.background = "";
    //   record.style.color = "";
    //   // mediaRecorder.requestData();

    //   stop.disabled = true;
    //   record.disabled = false;

    //   clearInterval(timer);
    //   seconds = 0;
    //   minutes = 0;
    //   hours = 0;
    // }

    mediaRecorder.onstop = function (e) {
      //var clipName = prompt('Enter a name for your sound clip?', cName);

      $("#dialog").dialog("open");
      console.log(clipName);
      var lastName = 1;
      audio = document.createElement('audio');
      audio.addEventListener("play", onAudio);
      audio.classList.add('audTag');
      audio.setAttribute('controls', '');

      var cc = navigator.userAgent.indexOf("Chrome") > -1;
      if (cc) {
        var chromeVer = getChromeVersion();
        if (chromeVer > 58) {
          audio.classList.add("recording");
        }
      } else {
        audio.classList.add("recording");
      }

      audio.controls = true;
      var blob = new Blob(chunks, { type: 'audio/mp3' });  // F1
      chunks = [];
      var audioURL = window.URL.createObjectURL(blob);
      audio.src = audioURL;
      console.log("recorder stopped");
      lastName = clipArr.length ? (parseInt(clipArr[clipArr.length - 1].replace("Clip ", ""))) : 0;
      console.log("MAX: ", lastName + 1, clipArr.length);
      lastName = Math.max(lastName + 1, clipArr.length);
      current_ID = lastName;
      audio.setAttribute("id", "clip" + current_ID);
      cName = "Clip " + (lastName);
      clipArr.push(cName);
      $("#inp").val(cName);
    }

    mediaRecorder.ondataavailable = function (e) {
      chunks.push(e.data);
    }
  })
  .catch(function (err) {
    /* handle the error */
  });
console.log(navigator)


function onAudio(iid) {
  var sounds = document.getElementsByTagName('audio');
  for (i = 0; i < sounds.length; i++) {
    if (sounds[i].id == iid.target.id)
      continue;
    sounds[i].pause();
  }
}

function customTimer(clipContainer, audio) {
  var tDiv = document.createElement("div");
  clipContainer.appendChild(tDiv);
  tDiv.innerHTML = "/ " + cTime;

  // tDiv.style.position = 'absolute';
  tDiv.style.width = '75px';
  tDiv.style.top = clipContainer.offsetTop + (audio.offsetHeight / 2) - (tDiv.offsetHeight / 2) + "px";
  tDiv.style.left = '60px';
  tDiv.style.color = '#5a5a5a';

  var cc = navigator.userAgent.indexOf("Chrome") > -1;
  if (cc) {
    var chromeVer = getChromeVersion();
    if (chromeVer > 58) {
      tDiv.style.fontSize = "0.6rem";
      tDiv.style.top = (clipContainer.offsetTop - 2) + (audio.offsetHeight / 3) - (tDiv.offsetHeight / 2) + "px";
      tDiv.style.left = '50px';
    }
  }
  //tDiv.style.visibility= 'hidden';
}

function updateTiming() {
  seconds++;
  if (seconds >= 60) {
    seconds = 0;
    minutes++;
    if (minutes >= 60) {
      minutes = 0;
      hours++;
    }
  }

  cTime = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

  //console.log("TIME: ", cTime, minutes, seconds);
}



function visualize(stream) {
  var source = audioCtx.createMediaStreamSource(stream);

  var analyser = audioCtx.createAnalyser();
  analyser.fftSize = 2048;
  var bufferLength = analyser.frequencyBinCount;
  var dataArray = new Uint8Array(bufferLength);

  source.connect(analyser);
  //analyser.connect(audioCtx.destination);

  WIDTH = canvas.width
  HEIGHT = canvas.height;

  draw()

  function draw() {
    requestAnimationFrame(draw);
    analyser.getByteTimeDomainData(dataArray);

    canvasCtx.fillStyle = 'rgb(200, 200, 200)';
    canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

    canvasCtx.lineWidth = 2;
    canvasCtx.strokeStyle = 'rgb(0, 0, 0)';

    canvasCtx.beginPath();

    var sliceWidth = WIDTH * 1.0 / bufferLength;
    var x = 0;

    for (var i = 0; i < bufferLength; i++) {

      var v = dataArray[i] / 128.0;
      var y = v * HEIGHT / 2;

      if (i === 0) {
        canvasCtx.moveTo(x, y);
      } else {
        canvasCtx.lineTo(x, y);
      }

      x += sliceWidth;
    }

    canvasCtx.lineTo(canvas.width, canvas.height / 2);
    canvasCtx.stroke();

  }
}

