const BASEURL = "https://files.colormatic.org/"

var videoplayer = document.getElementById("videoplayer");
var videotitle = document.getElementById("videotitle");
var videodescription = document.getElementById("videodescription");
var videodownload = document.getElementById("videodownload");
var sourcedownload = document.getElementById("sourcedownload");

var params = new URLSearchParams(window.location.search);
function getParam(paramName) {
  return params.get(paramName);
}

async function getJSON(url) {
  const response = await fetch(url);
  if(!response.ok)
    throw new Error(response.statusText);

  const data = response.json();
  return data;
}

function getVideo(cname, vname) {
  getJSON(BASEURL + cname + "/videos/data/" + vname + ".json").then((data) => {
    videoURL = BASEURL + cname + "/videos/raw/" + data.video_file + "." + data.video_format;
    videoplayer.setAttribute("poster", BASEURL + cname + "/videos/thumbnail/" + data.thumbnail);
    var videosource = document.createElement("source");
    videosource.setAttribute("src", videoURL);
    videosource.setAttribute("type", "video/" + data.video_format);
    videoplayer.appendChild(videosource);

    document.title = data.title;
    videotitle.appendChild(document.createTextNode(data.title));
    data.description.forEach((iter) => { // TODO: Detect if one of these lines contains a link and if so, make it a link
      videodescription.appendChild(document.createTextNode(iter));
      videodescription.appendChild(document.createElement("br"));
    });

    videodownload.setAttribute("href", BASEURL + cname + "/videos/raw/" + data.video_file + "." + data.video_format);
    videodownload.setAttribute("download", data.video_file + "." + data.video_format);
    sourcedownload.setAttribute("href", BASEURL + cname + "/videos/source/" + data.source_file + "." + data.source_format);
    sourcedownload.setAttribute("download", data.source_file + "." + data.source_format);

  }).catch((error) => {
    console.error(error);
  });
}

getVideo(getParam("c"), getParam("v"));