<script lang="ts">
  import type { Editor } from 'codemirror'
  import { onMount } from 'svelte'
  import { debounce } from 'lodash-es'
  import * as brotli from '$lib/brotli'
  import * as lzma from '$lib/lzma'
  import { byId } from '$lib/utils'
  import TopBar from '../components/TopBar.svelte'

  const algorithm: {
    compress: (data: string) => Promise<string>
    decompress: (data: string) => Promise<string>
  } = brotli
  
  const host = window.location.protocol + '//' + window.location.host + '/'

  let editor: Editor | null = null
  const readOnly = false

  let charLen = 0
  let compressed: string = ''
  let waiting = false
  $: shareUrl = host + compressed

  const updateCompressed = debounce(async () => {
    if (editor) {
      compressed = await algorithm.compress(editor.getValue())
      console.log(compressed)
    }
    waiting = false
  }, 1000)

  const initCodeEditor = () => {
    CodeMirror.modeURL = 'https://cdn.jsdelivr.net/npm/codemirror@5.65.5/mode/%N/%N.js'
    editor = new CodeMirror(byId('editor'), {
      lineNumbers: true,
      theme: 'dracula',
      readOnly: readOnly,
      lineWrapping: false,
      scrollbarStyle: 'native',
    }) as Editor
    console.log(editor)
    if (readOnly) {
      document.body.classList.add('readonly')
    }

    editor.on('change', async () => {
      if (editor) {
        waiting = true
        charLen = editor.getValue().length
        updateCompressed()
      }
    })
  }

  onMount(async () => {
    initCodeEditor()
  })
</script>

<div class="flex flex-col font-mono h-screen bg-gray-700">
  {#if !!editor}
    <TopBar {editor} />
  {/if}

  <div id="editor" class="grow overflow-hidden" />
  {editor?.getValue()}

  <div class="p-2 text-sm">
    Data length: {charLen}
    | Link length: {waiting ? '?' : shareUrl.length}
    ({waiting || !compressed.length || !charLen
      ? '?'
      : Math.round((shareUrl.length / charLen) * 100)}% of original)
  </div>
</div>

<style>
  :global(div.CodeMirror) {
    height: 100%;
  }
</style>
