<script setup lang="ts">
import { onMounted, computed, watch } from 'vue';
import { ElLoading  } from 'element-plus';
import Postmate from 'postmate';
import { createRenderer, createProvider } from '@vtj/renderer'
import { useQuery } from '@tanstack/vue-query';

import { LowCodeService } from './service'

import { getFile } from './io';

const lowCodeService = new LowCodeService();

const handshake = new Postmate.Model({});

const model = {
  name: '',
  applicationId: -1,
  projectId: -1,
  fileId: '',
  url: '',
}

const { data: file, isFetching } = useQuery({
  queryKey: ['getFile'],
  queryFn: async () => {
    await handshake.then(parent => {
    parent.emit('sync-context', 'Hello, World!');
    Object.assign(model, parent.model);
    console.log('model', model);
  });
    return getFile(model.fileId);
  },
});

watch(isFetching, (newVal) => {
  if (newVal) {
    ElLoading.service({
      text: '低代码文件加载中...',
    });
  } else {
    ElLoading.service().close();
  }
});

const { provider, onReady } = createProvider({
  // runtime: 'web',
  service: lowCodeService,
  project: {
    id: '4'
  },
});


onReady(() => {
  console.log('onReady');
});

const renderer = computed(() => {
  console.log(file?.value?.dsl.id);
  if (file?.value?.dsl) {
    return createRenderer({ dsl: file.value.dsl }).renderer;
  }
  return null;
});
</script>

<template>
  <component :is="renderer" v-if="renderer" />
</template>
