/**
 * Helpers and constants related to Clips URLs
 */
export const CLIPS_DOMAIN = 'clips.twitch.tv';
export const CLIPS_EMBED_URL = `https://${CLIPS_DOMAIN}/embed`;

// Matches space-delimited clips URLs. Captures slug and channel.
export const CLIPS_URL_REGEX = new RegExp(`(?:^|\\s)(?:https?\:\/\/)?${CLIPS_DOMAIN}/(\\w+)(?:\/)?(\\w+)?(?:\/edit)?(?:$|\\s)`);
export const CLIPS_HOSTNAME = 'clips.twitch.tv';

// Unused
export function containsClipURL(str) {
  str = str || '';
  return CLIPS_URL_REGEX.test(str);
}

// Gets first clips URL match and returns the channel and slug
// Unused
export function getSlugAndChannel(clipUrl) {
  clipUrl = clipUrl || '';
  let matches = clipUrl.match(CLIPS_URL_REGEX) || [];

  const isLegacyClip = matches[2] && matches[2] !== 'edit';
  const slug = (isLegacyClip) ? `${matches[1]}/${matches[2]}` : matches[1];

  return { slug };
}

// Specialized function for extracting clip info from a chat message
export function extractFirstClipInfo(message) {
  message = message || '';
  let matches = message.match(CLIPS_URL_REGEX);
  if (matches === null) {
    return {};
  }

  const isLegacyClip = matches && matches[2] && matches[2] !== 'edit';

  if (matches && matches.length > 0) {
    let startIndex = matches.index;
    let endIndex = matches.index + matches[0].length;

    const slug = (isLegacyClip) ? `${matches[1]}/${matches[2]}` : matches[1];

    return {
      index: [startIndex, endIndex],
      slug
    };
  }

  return {};
}

export function generateClipsURL(slug) {
  return `https://${CLIPS_DOMAIN}/${slug}`;
}
