<script setup lang="ts">
import { onBeforeUpdate, inject } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { oneDark } from '@codemirror/theme-one-dark'
import { createTheme} from 'thememirror';
import {tags as t} from '@lezer/highlight';
import {xml} from '@codemirror/lang-xml'
import {json} from '@codemirror/lang-json'
import {html} from '@codemirror/lang-html'

const props= defineProps({
  code : {
      type: String,
      required: true
  },
  config: {
      type: Object,
      required: true
    },
})

const lightTheme = createTheme({
	variant: 'light',
	settings: {
		background: '#FFFFFF',
		foreground: '#000000',
		caret: '#000000',
		selection: '#80C7FF',
		gutterBackground: '#FFFFFF',
		gutterForeground: '#00000070',
		lineHighlight: '#C1E2F840',
	},
	styles: [
		{
			tag: t.comment,
			color: '#AAAAAA',
		},
		{
			tag: [t.keyword, t.operator, t.typeName, t.tagName, t.propertyName],
			color: '#2F6F9F',
			fontWeight: 'bold',
		},
		{
			tag: [t.attributeName, t.definition(t.propertyName)],
			color: '#4F9FD0',
		},
		{
			tag: [t.className, t.string, t.special(t.brace)],
			color: '#CF4F5F',
		},
		{
			tag: t.number,
			color: '#CF4F5F',
			fontWeight: 'bold',
		},
		{
			tag: t.variableName,
			fontWeight: 'bold',
		},
	],
});

const emit = defineEmits(
  [
    'update:updatedCode'
  ]
)

const theme : string = inject('theme')!;
let extensions = parseExtensions();

onBeforeUpdate( () => { extensions = parseExtensions(); } )

function dataUpdated(newData:String){
  emit('update:updatedCode',newData)
}

function selectTheme() {
  if (isDarkModeSet())
    return oneDark;
  else
    return lightTheme;
}

function isDarkModeSet(){
  return localStorage.theme == "dark";
}

function parseExtensions(){
  return  [
      selectTheme(),
      parseLanguage(props.config.language),
  ]
}

function parseLanguage(name: String){
  switch(name.toUpperCase()){
    case "JSON": {
      return json();
    }
    case "HTML": {
      return html();
    }
    default: {
      return xml();
    }
  }
}




</script>

<template>
  <div class="editor w-full h-full rounded-2xl overflow-x-auto">
    
    <codemirror
      :key="theme"
      style="height: 100%; width: 100%; padding:1rem ; border-radius: 1rem; font-size: large;"
      :model-value="code"
      @update:model-value="dataUpdated"
      :extensions="extensions"
      :disabled="config.disabled"
      />
    
  </div>
</template>