
<template>
  <div class="header-items document-editor-header">
    <div class="rect-button white" @click="cancel">{{ $t('cancel') }}</div>
    <div class="right-container">
      <div class="rect-button blue" :class="{ 'disabled': !docEditorOperationList.length }" @click="save">{{ $t('documentEditor.save') }}</div>
      <div class="rect-button blue" :class="{ 'disabled': !docEditorOperationList.length }" @click="saveFileAs">{{ $t('documentEditor.saveAs') }}</div>
    </div>
  </div>
</template>

<script setup>
import { computed, watch } from 'vue'
import { useViewerStore } from '@/stores/modules/viewer'
import { useDocumentStore } from '@/stores/modules/document'
import core from '@/core'
import { saveAs } from 'file-saver'

const useViewer = useViewerStore()
const useDocument = useDocumentStore()

const docEditorOperationList = computed(() => useDocument.getDocEditorOperationList)
const toolMode = computed(() => useViewer.getToolMode)
const scrollMode = computed(() => useViewer.getScrollMode)
const pageMode = computed(() => useViewer.getPageMode)

watch(toolMode, (newToolMode, oldToolMode) => {
  if (oldToolMode === 'document') {
    useDocument.setDocEditorOperationList('reset')
  }
})

const cancel = () => {
  useDocument.setToolState('')
  useViewer.setActiveToolMode('view')
  useViewer.setCompareStatus('')
  core.saveDocumentEdit('cancel')
}

const save = async () => {
  useDocument.resetSetting()
  useDocument.setToolState('')
  useViewer.setActiveToolMode('view')
  useViewer.setUpload(true)
  useViewer.setUploadLoading(true)
  const oldScale = useViewer.getScale

  const newUrl = await core.saveDocumentEdit()
  const pwd = useDocument.getPassword
  await core.loadDocument(newUrl, {
    password: pwd
  })
  useDocument.setCurrentPdfData(newUrl)
  const totalPages = core.getPagesCount()
  useDocument.setTotalPages(totalPages)
  useDocument.setOutline(core.getOutlines())
  useViewer.setCurrentPage(1)
  core.switchScrollMode(scrollMode.value === 'Vertical' ? 0 : 1)
  core.switchSpreadMode(pageMode.value)
  useViewer.setCurrentScale(oldScale / 100)
  core.scaleChanged(oldScale / 100)

  useViewer.setUploadLoading(false)
}

const saveFileAs = async () => {
  const { blobData, filename } = await core.saveDocumentEdit('saveAs')
  saveAs(blobData, filename)
}
</script>

<style lang="scss">
.document-editor-header {
  justify-content: space-between;
}
</style>
