<script setup lang="ts">

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

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

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

const currentPage = ref(0);

const bellhop = new Bellhop();
bellhop.on("ready", () => {
  bellhop.send("render", {defaultPage: props.defaultPage, defaultZoom: props.defaultZoom, metas: props.metas});
});

bellhop.on("pageChange", ({data}: {data: Pagination}) => {
  if (currentPage.value != data.current) {
    currentPage.value = data.current;
    emit("paginationChange", data);
  }
})
bellhop.on("zoomChange", ({data}: {data: {zoom: number}}) => {
  emit("zoomChange", data.zoom);
});

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

watch(() => props.metas, async () => {
  iframeSrc.value = props.dev ? 'http://localhost:5175' : (`${props.engineBaseUrl ? props.engineBaseUrl : ''}/cf-player/document-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 => {
  bellhop.send("goto", pos);
}

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

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

const zoomTo = (zoom: number): void => {
  bellhop.send("zoomTo", {zoom});
}

defineExpose({
  prev,
  next,
  goto,
  zoomIn,
  zoomOut,
  zoomTo,
});

</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>
