import 'dart:async';
// ignore: avoid_web_libraries_in_flutter
import 'dart:html' as html;

class JsLibraryImportUtil {
  static const packageName = "fis_lib_media_rt";
  static Future<void> import(String libPath) {
    return _importScript(_handleLibUrl(libPath, packageName));
  }

  static bool isImported(String url) {
    final html.Element head = html.querySelector('head')!;
    return _isLoaded(head, url);
  }

  static String _handleLibUrl(String url, String packageName) {
    if (url.startsWith("./")) {
      url = url.replaceFirst("./", "");
      return "./assets/packages/$packageName/$url";
    }
    if (url.startsWith("assets/")) {
      return "./assets/packages/$packageName/$url";
    } else {
      return url;
    }
  }

  static Future<void> _importScript(String src) {
    final head = html.querySelector('head')!;

    if (isImported(src)) {
      return Future.value();
    } else {
      final scriptTag = _createScriptTag(src);
      head.children.add(scriptTag);
      return scriptTag.onLoad.first;
    }
  }

  static html.ScriptElement _createScriptTag(String src) {
    final html.ScriptElement script = html.ScriptElement()
      ..type = "text/javascript"
      ..charset = "utf-8"
      ..async = true
      ..src = src;
    return script;
  }

  static bool _isLoaded(html.Element head, String url) {
    if (url.startsWith("./")) {
      url = url.replaceFirst("./", "");
    }
    for (var element in head.children) {
      if (element is html.ScriptElement) {
        if (element.src.endsWith(url)) {
          return true;
        }
      }
    }
    return false;
  }
}
