<script setup lang="ts">
import { useStore } from '@/store'
const store = useStore()
import { ref, shallowRef, watch } from 'vue'
import VCollaps from './VCollaps.vue';

//see https://github.com/imguolao/monaco-vue#vite
import { loader } from "@guolao/vue-monaco-editor"
import * as monaco from "monaco-editor"
import editorWorker from "monaco-editor/esm/vs/editor/editor.worker?worker"
import jsonWorker from "monaco-editor/esm/vs/language/json/json.worker?worker"
import cssWorker from "monaco-editor/esm/vs/language/css/css.worker?worker"
import htmlWorker from "monaco-editor/esm/vs/language/html/html.worker?worker"
import tsWorker from "monaco-editor/esm/vs/language/typescript/ts.worker?worker"
import { storeToRefs } from 'pinia';
import type { IMappingEntry } from '@/ServerConfig';
self.MonacoEnvironment = {
  getWorker(_, label) {
    if (label === "json") {
      return new jsonWorker()
    }
    if (label === "css" || label === "scss" || label === "less") {
      return new cssWorker()
    }
    if (label === "html" || label === "handlebars" || label === "razor") {
      return new htmlWorker()
    }
    if (label === "typescript" || label === "javascript") {
      return new tsWorker()
    }
    return new editorWorker()
  }
}
loader.config({ monaco })
const MONACO_EDITOR_OPTIONS = {
  automaticLayout: true,
  formatOnType: true,
  formatOnPaste: true,
}
const { selectedNode } = storeToRefs(store)
const code=ref("");
let dirty=false;

watch(selectedNode, () => {
  if (!selectedNode.value)
    return;
  if (!selectedNode.value.nodeId.value)
    return;
  const m = store.addressSpace?.mapping.get(selectedNode.value.nodeId.toString());
  code.value = m?.read || "";
  dirty=false;
});

const editorRef = shallowRef()
const handleMount = (editor: any) => {
  editorRef.value = editor;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const onChange = (value: string | undefined, event: monaco.editor.IModelContentChangedEvent) => {
  if(!store.selectedNode)
    return;
  if(!value)
    return;
  code.value=value;
}

function formChanged(){
  dirty=true;
}

function okPressed() {
  if(!dirty)
    return;
  if(!selectedNode.value)
    return;
  store.addressSpace?.mapping.set(selectedNode.value.nodeId.toString(), {path: selectedNode.value.nodeId.toString(), read: code.value, write: ""} as IMappingEntry)
  dirty=false;
}
defineExpose({ okPressed })
</script>

<template>
  <VCollaps :selected=false name="Mapping"  @change="formChanged()">
      <div class="card-text" v-if="selectedNode">
        <vue-monaco-editor
          v-model:value="code"
          height= "12em"
          theme="vs-dark"
          language="javascript"
          :options="MONACO_EDITOR_OPTIONS"
          @mount="handleMount"
          @change="onChange"
        />
      </div>
  </VCollaps>
</template>

<style scoped></style>