<script setup lang="ts">
import { computed } from 'vue';
import { Codemirror } from 'vue-codemirror';
import { json } from '@codemirror/lang-json';
import { oneDark } from '@codemirror/theme-one-dark';
import { EditorView } from '@codemirror/view';
import { useSettingsStore } from '../stores/settingsStore';

const props = withDefaults(defineProps<{
  modelValue?: string;
  placeholder?: string;
  readOnly?: boolean;
  language?: 'json' | 'text';
}>(), {
  modelValue: '',
  placeholder: '',
  readOnly: false,
  language: 'text',
});

const emit = defineEmits<{
  'update:modelValue': [value: string];
}>();

const settings = useSettingsStore();

const extensions = computed(() => {
  const theme = EditorView.theme({
    '&': {
      backgroundColor: 'transparent !important',
      height: '100%',
    },
    '.cm-content, .cm-gutter': {
      fontFamily: `${settings.editorFontFamily} !important`,
    },
    '.cm-gutters': {
      backgroundColor: 'transparent !important',
    },
  });

  return [
    oneDark,
    theme,
    ...(props.language === 'json' ? [json()] : []),
    ...(props.readOnly ? [EditorView.editable.of(false)] : []),
  ];
});
</script>

<template>
  <Codemirror
    :model-value="props.modelValue"
    :placeholder="props.placeholder"
    :style="{
      height: '100%',
      fontSize: settings.editorFontSize + 'px',
      fontFamily: settings.editorFontFamily,
    }"
    :autofocus="false"
    :indent-with-tab="true"
    :tab-size="2"
    :extensions="extensions"
    @update:model-value="emit('update:modelValue', $event)"
  />
</template>
