<script setup lang="ts">
    const props = defineProps<{
        SCRIPT_ID?: any,
        SCRIPT_SRC?: any,
        CONTAINER_ID?: any,
        options?: any,
        inside?: boolean,
        widgetKey?: any
    }>()

    const widgets : any = {};
    const instance = getCurrentInstance();

    const canUseDOM = () => {
        return typeof window !== 'undefined' && window.document && window.document.createElement;
    };
    const getScriptElement = () => {
        return document.getElementById(props.SCRIPT_ID);
    }
    const updateOnloadListener = (onload : any) => {
      const script : any = getScriptElement(); 
      const oldOnload = script.onload;
      return script.onload = () => {
        oldOnload();
        onload();
      };
    }
    const scriptExists = () => {
      return getScriptElement() !== null;
    }
    const appendScript = (onload : any) => {
      if (!canUseDOM()) {
        onload();
        return;
      }

      if (scriptExists()) {
        if (typeof window[props.widgetKey] === 'undefined') {
          updateOnloadListener(onload);
          return;
        }
        onload();
        return;
      }
      const script = document.createElement('script');
      script.id = props.SCRIPT_ID;
      script.type = 'text/javascript';
      script.async = true;
      script.src = props.SCRIPT_SRC;
      script.onload = onload;
      if (props.inside) document.getElementById(props.CONTAINER_ID) && document.getElementById(props.CONTAINER_ID).appendChild(script);
      else {
        document.getElementsByTagName('body')[0].appendChild(script);
      }
    }
    const initWidget = (key: any) => {
      if (typeof widgets[key].key === 'undefined') {
        return;
      }
      widgets[key].script()
    }

    onMounted(async () => {
      await Object.assign(widgets, { 
        FireAnt: {
          script: () => new window.FireAnt.MarketsWidget({ container_id: props.CONTAINER_ID, ...props.options }),
          key: window.FireAnt
        },
        TradingView: {
          script: () => new window.TradingView.widget({ container_id: props.CONTAINER_ID, ...props.options }),
          key: window.TradingView
        }
      })
      appendScript(initWidget(props.widgetKey));
    })
</script>

<template>
  <div :key="props.CONTAINER_ID" :id="props.CONTAINER_ID"></div>
</template>
