var idify = function idify(s) {
  return s.toLowerCase().replace(/[^a-z0-9]/g, "_").replace(/_+/g, "_");
};

export default (function (_ref) {
  var youtubeUrl = _ref.youtubeUrl,
      videoTitle = _ref.title,
      remote = _ref.remote,
      videoQuality = _ref.videoQuality,
      downloadPath = _ref.downloadPath,
      onProgress = _ref.onProgress,
      onComplete = _ref.onComplete,
      onChangeOverallProgress = _ref.onChangeOverallProgress;

  //let starttime = Date.now()
  var ytdl = remote.require("ytdl-core");

  var path = remote.require("path");

  var videoName = videoQuality.includes("audio") ? "".concat(idify(videoTitle) + ".mp3") : "".concat(idify(videoTitle) + ".mp4");
  var fullVideoPath = path.join(downloadPath, videoName);

  var writableVideoFile = remote.require("fs").createWriteStream(fullVideoPath);

  var videoFormat = videoName.endsWith(".mp3") ? "audio/mp3" : "video/mp4";
  var youtubeVideoWithOptions = ytdl(youtubeUrl, {
    format: videoFormat,
    quality: videoQuality !== null ? videoQuality : "highest"
  });
  youtubeVideoWithOptions.pipe(writableVideoFile);
  /*youtubeVideoWithOptions.once("response", () => {
    starttime = Date.now()
  })*/

  youtubeVideoWithOptions.on("progress", function (chunkLength, downloaded, total) {
    var percent = downloaded / total; // const downloadedMinutes = (Date.now() - starttime) / 1000 / 60
    // const downloadedPercentage = (percent * 100).toFixed(2)
    // const downloadedSize = (downloaded / 1024 / 1024).toFixed(2)
    // const downloadedMBs = (
    //   downloaded /
    //   1024 /
    //   1024
    // ).toFixed(2)
    // const totalSize = (total / 1024 / 1024).toFixed(2)
    // const informationText = `${downloadedPercentage}% downloaded (${downloadedMBs}MB of ${totalSize}MB)\nestimated time left: ${(downloadedMinutes / percent -downloadedMinutes).toFixed(2)}minutes`

    onProgress({
      progress: percent * 100
    });
    onChangeOverallProgress(percent * 100);
  });
  youtubeVideoWithOptions.on("end", function () {
    return onComplete(fullVideoPath);
  });
  return {
    cancel: function cancel() {
      youtubeVideoWithOptions.destroy();
    }
  };
});