<script setup lang="ts">

import {FileMetas, Pagination, Position} from "./model.ts";
import {nextTick, ref, toRaw, useTemplateRef, watch} from "vue";
import {Bellhop} from 'bellhop-iframe';

const props = withDefaults(defineProps<{
    metas: FileMetas,
    defaultPage?: number,
    defaultStep?: number,
    engineBaseUrl?: string,
    headless?: boolean,
    dev?: boolean
}>(), {
    defaultPage: 1,
    defaultStep: 1,
    headless: false,
    dev: false,
});

const emit = defineEmits<{
    paginationChange: [pagination: Pagination];
    loading: [boolean];
}>();

const iframeEl = useTemplateRef("iframe");
const iframeSrc = ref<string|null>(null);

const bellhop = new Bellhop();

bellhop.on("ready", () => {
  bellhop.send("render", {defaultPage: props.defaultPage, defaultStep: props.defaultStep, metas: toRaw(props.metas.animation)});
});

bellhop.on("pageChange", ({data}: {data: Pagination}) => {
  emit("paginationChange", Object.assign({}, data, {total: props.metas.page}));
})

watch(() => props.metas, async () => {
  iframeSrc.value = props.dev ? 'http://localhost:5174' : (`${props.engineBaseUrl ? props.engineBaseUrl : ''}/cf-player/ppt-engine/index.html`);
  await nextTick();
  bellhop.connect(iframeEl.value as HTMLIFrameElement);
}, { immediate: true })

const prev = (): void => {
  bellhop.send("prev");
}

const next = (): void => {
  bellhop.send("next");
}

const goto = (pos: Position): void => {
  pos.step = pos.step ? pos.step : 1;
  bellhop.send("goto", pos);
}

defineExpose({
    prev,
    next,
    goto,
});

</script>

<template>
    <div ref="containerEl">
      <iframe ref="iframe" :src="iframeSrc" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0" v-if="iframeSrc" />
    </div>
</template>
