<script setup lang="ts">
import { tryOnMounted } from '@vueuse/core';
import { LogicFlow } from '@logicflow/core';

import { provideLogicFlow, tryLogicFlow } from './use';
import { EndNode, StartNode } from './nodes';
import { PolylineEdge } from './edges';

import type { LogicFlowInstance, LogicFlowOptions } from './types';

defineOptions({
  name: 'VLogicFlow',
});
const props = defineProps<{ options?: LogicFlowOptions; loading?: boolean }>();
const emits = defineEmits<{ loaded: [LogicFlowInstance] }>();
const containerRef = useTemplateRef('container');
tryOnMounted(() => {
  const options = {
    ...props.options,
    parentTransform: tryLogicFlow()?.graphModel.transformModel,
    container: containerRef.value!,
  };
  const lf = new LogicFlow(options);
  lf.register(PolylineEdge);
  lf.register(StartNode);
  lf.register(EndNode);
  lf.setDefaultEdgeType('custom-polyline-edge');
  provideLogicFlow(lf);
  emits('loaded', lf);
});
</script>

<template>
  <div class="v-logic-flow-wrapper">
    <a-spin :spinning="props.loading" :delay="200">
      <div class="v-logic-flow" v-bind="$attrs">
        <main ref="container"></main>
        <slot name="top"></slot>
        <slot name="panel" v-if="!props.loading"></slot>
        <slot name="float" v-if="!props.loading"></slot>
      </div>
    </a-spin>
  </div>
</template>

<style scoped lang="scss">
.v-logic-flow-wrapper {
  :deep(.ant-spin-nested-loading) {
    position: relative;
    height: 100%;
    .ant-spin {
      max-height: 100%;
    }

    > div {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }
  }
}
.v-logic-flow {
  width: 100%;
  height: 100%;
  position: relative;
  > main {
    width: 100%;
    height: 100%;
  }
}
.panel-wrapper {
  position: absolute;
  top: 0;
  left: 0;
}
</style>
