/*!
 * Copyright (c) 2021, 2022 Eclipse Foundation, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * Contributors:
 *   Zhou Fang <zhou.fang@eclipse-foundation.org>
 *   Eric Poirier <eric.poirier@eclipse-foundation.org>
 * 
 * SPDX-License-Identifier: EPL-2.0
 */

export const displayErrMsg = (element, err = '', errText = 'Sorry, something went wrong, please try again later.') =>
  (element.innerHTML = `<div class="alert alert-danger" role="alert"><p><strong>Error ${err}</strong></p> <p>${errText}</p></div>`);

const absUrlPattern = /^[a-zA-Z]+:\/\//;

export const validateURL = (url) => {
  const isAbsolute = url.match(absUrlPattern);
  const base = isAbsolute ? undefined : window.location.href;
  
  let isValidate;
  try {
    // This will fail if the url is not valid
    new URL(url, base);
    isValidate = true;
  } catch (error) {
    isValidate = false;
  }
  return isValidate;
};

export const scrollToAnchor = () => {
  const elementId = location.hash.replace('#', '');
  const element = document.getElementById(elementId);
  element.scrollIntoView();
}