function getAllCss() {
  var css = "";
  var styleTags = document.getElementsByTagName("style");

  //loop over all the style tags
  for (var i = 0; i < styleTags.length; i++) {
    css += styleTags[i].innerHTML;
  }

  //loop over all the external stylesheets
  for (var i = 0; i < document.styleSheets.length; i++) {
    var currentSheet: any = document.styleSheets[i];
    try {
      //loop over all the styling rules in this external stylesheet      
      for (var e = 0; e < currentSheet.cssRules.length; e++) {
        css += currentSheet.cssRules[e].cssText; //extract all the styling rules
      }
    } catch (e) { /* Continue here. Nothing much we can do */ }
  }

  return css;
}

function getAllLinks() {
  var links = "";
  var linkTags = document.getElementsByTagName("link");

  for (var i = 0; i < linkTags.length; i++) {
    links += linkTags[i].href + ",";
  }

  return links;
}

export function isSemanticUiLoaded(): boolean {
  console.log('checking if semantic ui is loaded via css');
  const css = getAllCss();
  const links = getAllLinks();

  const isSemanticUiLoaded =
    (css.indexOf('https://github.com/Semantic-Org/Semantic-UI') > -1) ||
    (css.indexOf('http://www.semantic-ui.com/') > -1) ||
    (links.indexOf('//cdn.jsdelivr.net/npm/semantic-ui') > -1 && links.indexOf('semantic-ui') > -1);

  return isSemanticUiLoaded;
}

export function loadSemanticUiCssIfRequired() {
  if (!isSemanticUiLoaded()) {
    console.log('semantic is not loaded - loading css')
    var css = document.createElement('link');
    css.rel = 'stylesheet';
    css.href = '//cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css';
    document.head.appendChild(css);
  }
}