/* eslint-disable no-useless-escape */
const config = require("../config");
const Vimeo = require("vimeo").Vimeo;
const client = new Vimeo(config.vimeo.CLIENT_ID, config.vimeo.CLIENT_SECRET, config.vimeo.ACCESS_TOKEN);

function parseVideo(url) {
  /*     - Supported YouTube URL formats:
      - http://www.youtube.com/watch?v=My2FRPA3Gf8
      - http://youtu.be/My2FRPA3Gf8
      - https://youtube.googleapis.com/v/My2FRPA3Gf8
    - Supported Vimeo URL formats:
      - http://vimeo.com/25451551
      - http://player.vimeo.com/video/25451551
    - Also supports relative URLs:
      - //player.vimeo.com/video/25451551
 */
  var type = undefined;
  url.match(
    /(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/
  );

  if (RegExp.$3.indexOf("youtu") > -1) {
    type = "youtube";
  } else if (RegExp.$3.indexOf("vimeo") > -1) {
    type = "vimeo";
  }

  return {
    type: type,
    id: RegExp.$6,
    class: type ? "video" : "unknown",
  };
}

function getIframeSource(iframeHtml) {
  const groups = iframeHtml.match(/\<iframe.+src\=(?:\"|\')(.+?)(?:\"|\')/);
  return groups[1];
}

function extractVimeoInformation(vimeoResponse) {
  return {
    duration: vimeoResponse.duration,
    name: vimeoResponse.name,
    description: vimeoResponse.description,
    link: vimeoResponse.link,
    type: vimeoResponse.type,
    stats: vimeoResponse.stats,
    files: vimeoResponse.files,
    download: vimeoResponse.download,
    pictures: vimeoResponse.pictures,
    embed: getIframeSource(vimeoResponse.embed.html),
  };
}

function extractProviderInfo(videoId) {
  return new Promise(function (resolve, reject) {
    client.request(
      {
        method: "GET",
        path: "/videos/" + videoId,
      },
      function (error, body, status_code, headers) {
        if (error) {
          console.error(error);
          resolve({});
        } else {
          if (body.status !== "available") {
            resolve({});
          } else {
            resolve(extractVimeoInformation(body));
          }
        }
      }
    );
  });
}

function determineProviderInfo(url) {
  console.log(url);

  if (!url)
    return {
      provider: undefined,
      code: undefined,
      class: undefined,
    };

  var info = parseVideo(url);
  return {
    provider: info.type,
    code: info.code,
    class: info.class,
  };
}

module.exports = {
  determineProviderInfo,
  extractProviderInfo,
};
