const regexEx = /^[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,16}\b([-a-zA-Z0-9@:%_+.~#?&/=\S]*)/;
const extraRegex = /(https?:\/\/)|(\/){2,}/; // no double slash

export const removeProtocol = (url) => url.replace(/https?:\/\//i, '').replace(/\/$/, '');
export const removeWorldWideWebPrefix = (url) => url.replace(/^www\./, '');

export const isValidPlaylistUrl = (url) => {
  const urlWithoutProtocol = removeProtocol(url).toLowerCase();

  return regexEx.test(url) && !extraRegex.test(urlWithoutProtocol) && url.substring(url.length - 1) !== '/';
};

export const matchedPlayersByURL = (url, players) => {
  const urlWithoutWorldWideWebPrefix = url ? removeWorldWideWebPrefix(url.toLowerCase()) : '';

  return players.filter((player) =>
    player.urlPrefix.find((playerUrl) =>
      urlWithoutWorldWideWebPrefix.includes(removeWorldWideWebPrefix(playerUrl.toLowerCase())),
    ),
  );
};

export const availablePlayers = (players, playlists) => {
  const usedPlayers = [...new Set(playlists.map((playlist) => playlist.playerId))];

  return players.filter((player) => !usedPlayers.includes(player.id));
};
