<template>
  <div class="app-page" @contextmenu.prevent>
    <Header />

    <div class="design-body">
      <Graphics ref="graphicsRef"/>
      <View />
      <div style="border-left: 1px solid var(--color-border);">
        <FitProps v-if="selections.mode === SelectionMode.Fit" />
        <FileProps v-else-if="selections.mode === SelectionMode.File" />
        <PenProps v-else-if="selections.mode === SelectionMode.Pen" :device-list="currentDevices" />
        <PensProps v-else />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Header from './components/Header.vue';
import Graphics from './components/Graphics.vue';
import View from './components/View.vue';
import FileProps from './components/FileProps.vue';
import PenProps from './components/PenProps.vue';
import PensProps from './components/PensProps.vue';
import FitProps from './components/FitProps.vue';

import { useSelection, SelectionMode } from '@/services/selections';
import { onMounted, onUnmounted, ref } from "vue";
import { DeviceItem, IframeMsg } from '@/types';
import { getVisual2DMsgType, Visual2DMsgType } from '.';
import { useModuleType } from '@/services/module-type';
import { graphicsRef } from '@/services/project';
import { useRoute } from 'vue-router';
import { saveModuleAndClose } from '@/utils';

const route = useRoute();
const { setModuleType } = useModuleType();
const currentDevices = ref<DeviceItem[]>([]);

onMounted(()=>{
  selections.mode = SelectionMode.File

  if (route.query.moduleType) {
    setModuleType(Number(route.query.moduleType))
  }

  window.addEventListener("message", handleMsg);

  const msg: IframeMsg = {
    msgType: getVisual2DMsgType(Visual2DMsgType.EditLoaded),
  };

  window.parent.postMessage(msg, "*");
})

onUnmounted(() => {
  window.removeEventListener("message", handleMsg);
});

const handleMsg = (e: MessageEvent<IframeMsg>) => {
  const { msgType, deviceList } = e.data;
  
  if (msgType === getVisual2DMsgType(Visual2DMsgType.SendDeviceData)) {
    currentDevices.value = deviceList as DeviceItem[];
  } else if (msgType === getVisual2DMsgType(Visual2DMsgType.SaveModule)) {
    saveModuleAndClose(e.data.close)
  }
};

const { selections } = useSelection();
</script>

<style lang="postcss" scoped>
.app-page {
  height: 100vh;

  .design-body {
    display: grid;
    grid-template-columns: 300px calc(100% - 601px) 301px;
    height: calc(100vh - 40px);
    border-top: 1px solid var(--color-border);
  }
}
</style>
