(function ($) {
  "use strict";

  const video = document.querySelector("video");
  var player = '';
  const source = video.getElementsByTagName("source")[0].src;

  const defaultOptions = {
    captions: { active: true, language: "fa" },
    tooltips: { controls: true, seek: true },
    controls: [
      "play-large",
      "play",
      "progress",
      "current-time",
      "mute",
      "volume",
      "captions",
      "settings",
      "airplay",
      "fullscreen",
    ],
    quality: { default: 720, options: [1080, 720, 480, 360, 240] },
    settings: ["captions", "quality"],
  };

  if (Hls.isSupported() && $("video").data("hls") == "on") {
    const hls = new Hls();
    hls.loadSource(source);
    hls.on(Hls.Events.MANIFEST_PARSED, function () {
      const availableQualities = hls.levels.map((l) => l.height);
      defaultOptions.quality = {
        default: availableQualities[0],
        options: availableQualities.reverse(),
        forced: true,
        onChange: (e) => updateQuality(e),
      };
      player = new Plyr(video, defaultOptions);
    });
    hls.attachMedia(video);
    window.hls = hls;
  } else {
    player = new Plyr(video, defaultOptions);
  }

  function updateQuality(newQuality) {
    window.hls.levels.forEach((level, levelIndex) => {
      if (level.height === newQuality) {
        window.hls.currentLevel = levelIndex;
      }
    });
  }

  $(document).on("click", ".select-lang a.active", function (e) {
    e.preventDefault();
  });

  $("track").each(function () {
    var track = $(this);
    switch (getExt(track.data('src'))) {
      case "srt":
        getTrackContent(track, track.data('src'));
        break;
      case "vtt":
        getTrackContent(track, track.data('src'), true);
        break;
      default:
        console.warn("Only .vtt and .srt formats are supported.");
        break;
    }
  });

  function getTrackContent(elem, url, e = false) {
    $.ajax({
      url: url,
      type: 'GET',
      success: function (text) {
        if (e === false) {
          elem.attr("src", vttToBlob(srtToVtt(text)));
        } else {
          elem.attr("src", vttToBlob(text));
        }
        elem.removeAttr("data-src");
      },
      error: function (error) {
        console.log(error)
      }
    });
    return false;
  }

  function srtToVtt(srtText) {
    return "WEBVTT \r\n\r\n".concat(
      srtText
        .replace(/{[\s\S]*?}/g, "")
        .replace(/\{\\([ibu])\}/g, "</$1>")
        .replace(/\{\\([ibu])1\}/g, "<$1>")
        .replace(/\{([ibu])\}/g, "<$1>")
        .replace(/\{\/([ibu])\}/g, "</$1>")
        .replace(/(\d\d:\d\d:\d\d),(\d\d\d)/g, "$1.$2")
        .concat("\r\n\r\n")
    );
  }

  function vttToBlob(vttText) {
    return URL.createObjectURL(
      new Blob([vttText], {
        type: "text/vtt",
      })
    );
  }

  function getExt(url) {
    if (typeof url == "undefined") return;
    if (url.includes("?")) {
      return getExt(url.split("?")[0]);
    }
    if (url.includes("#")) {
      return getExt(url.split("#")[0]);
    }
    return url.trim().toLowerCase().split(".").pop();
  }
})(jQuery);
