<template>
  <div ref="el" class="guns-editor-area" :style="{ width, height }"></div>
  <EditorWorker></EditorWorker>
</template>

<script setup>
import { onMounted, watch } from 'vue';
import { useMonacoEditor } from './index.hook';
import EditorWorker from './components/editor-worker.vue';

defineOptions({
    name: 'GunsMonacoEditor'
})

const props = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '90vh'
  },
  language: {
    type: String,
    default: 'typescript'
  },
  preComment: {
    type: String,
    default: ''
  },
  modelValue: {
    type: String,
    default: ''
  },
  editorOptions: {
    type: Object,
    default: () => ({})
  }
});

const emits = defineEmits(['blur', 'update:modelValue']);

const { el, updateVal, getEditor, createEditor } = useMonacoEditor(props.language);

const updateMonacoVal = _val => {
  const { modelValue, preComment } = props;
  const val = preComment ? `${preComment}\n${_val || modelValue}` : _val || modelValue;
  updateVal(val);
};

onMounted(() => {
  const monacoEditor = createEditor(props.editorOptions);
  monacoEditor?.onDidChangeModelContent(() => {
    emits('update:modelValue', monacoEditor?.getValue());
  });
  monacoEditor?.onDidBlurEditorText(() => {
    emits('blur');
  });
  updateMonacoVal();
});

watch(
  () => props.modelValue,
  val => {
    val !== getEditor()?.getValue() && updateMonacoVal(val);
  }
);
</script>

<style lang="less" scoped>
.guns-editor-area {
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  padding: 5px;
  padding-left: 0;
  box-sizing: border-box;
  background-color: rgba(0, 0, 0, 0);
  :deep(.margin, .monaco-editor, .inputarea.ime-input) {
    background-color: rgba(0, 0, 0, 0);
  }

  :deep(.monaco-editor-background) {
    background-color: rgba(0, 0, 0, 0);
  }
}
</style>
