<template>
  <div class="toolbar" v-show="isShowToolbar" :class="{ security: toolMode === 'security', editor: toolMode === 'editor', disabled: isDisabledHeader }">
    <div v-show="isMobileDevice && isShowLeftBtn" class="scroll-container left">
      <Button class="flip-button" @click="scrollLeft"><ArrowPrev /></Button>
    </div>
    <div class="tools" ref="toolbarRef" @scroll="handleScroll">
      <!-- Annotation -->
      <Annotate v-if="toolMode === 'annotation'" :items="tools[toolMode]" />
      <!-- Content Editor -->
      <ContentEditorToolBar v-else-if="toolMode === 'editor'" :items="tools[toolMode]"/>
      <template v-else v-for="(item, index) in tools[toolMode]" :key="`${item.type}-${item.dataElement || index}`">
        <!-- Form -->
        <TextFieldButton v-if="item.type === 'textFieldButton' && !item.hidden" :item="item" :data-element="item.dataElement" />
        <CheckBoxButton v-else-if="item.type === 'checkBoxButton' && !item.hidden" :item="item" :data-element="item.dataElement" />
        <RadioButton v-else-if="item.type === 'radioButton' && !item.hidden" :item="item" :data-element="item.dataElement" />
        <ListBox v-else-if="item.type === 'listBox' && !item.hidden" :item="item" :data-element="item.dataElement" />
        <ComboBox v-else-if="item.type === 'comboBox' && !item.hidden" :item="item" :data-element="item.dataElement" />
        <PushButton v-else-if="item.type === 'pushButton' && !item.hidden" :item="item" :data-element="item.dataElement" />

        <!-- Security -->
        <SecurityToolbar v-else-if="item.type === 'securityToolbar'" :item="item" />
        <!-- <WatermarkSelect v-if="item.type === 'watermarkSelect'" :item="item" /> -->

        <!-- Compare -->
        <ComparedToolbar v-else-if="item.type === 'comparedToolbar'" />
        <!-- Signature -->
        <SignatureToolBar v-else-if="item.type === 'signatureToolBar'" />
      </template>
    </div>
    <div v-show="isMobileDevice && isShowRightBtn" class="scroll-container right">
      <Button class="flip-button" @click="scrollRight"><ArrowNext /></Button>
    </div>
    <input v-if="isMobileDevice" type="file" id="annotaionImageInput" accept=".png, .jpg, .jpeg" style="display: none;" @change="handleFile" @click="clickUpload" name="annotaion">
  </div>
</template>

<script setup>
import { ref, computed, nextTick, watch, getCurrentInstance } from 'vue'
import { useViewerStore } from '@/stores/modules/viewer'
import { useDocumentStore } from '@/stores/modules/document'
import { isMobileDevice } from '@/helpers/device'
import MessageError from '@/assets/icons/icon-message-error.svg'
import core from '@/core'

const instance = getCurrentInstance().appContext.app.config.globalProperties
const useViewer = useViewerStore()
const useDocument = useDocumentStore()

const tools = useViewer.getToolItems
const compareStatus = computed(() => useViewer.getCompareStatus)
const isDisabledHeader = computed(() => useViewer.getDisabledHeader)
const toolMode = computed(() => useViewer.getToolMode)
const activeTool = computed(() => useDocument.getActiveTool)
const currentPage = computed(() => useViewer.getCurrentPage)

const isShowToolbar = ref(false)
const toolbarRef = ref(null)
const isShowLeftBtn = ref(false)
const isShowRightBtn = ref(false)

watch(toolMode, async (newValue, oldValue) => {
  isShowToolbar.value = !(['view', 'document'].includes(newValue) || (newValue === 'compare' && compareStatus !== 'finished'))
  isShowLeftBtn.value = false
  isShowRightBtn.value = false

  await nextTick()
  if (isShowToolbar.value) {
    if (toolbarRef.value && toolbarRef.value.scrollLeft > 0) isShowLeftBtn.value = true
    if (toolbarRef.value && toolbarRef.value.scrollLeft + toolbarRef.value.clientWidth < toolbarRef.value.scrollWidth) isShowRightBtn.value = true
  }
})

watch(compareStatus, async (newValue, oldValue) => {
  isShowToolbar.value = !(['view', 'document'].includes(toolMode.value) || (toolMode.value === 'compare' && newValue !== 'finished'))
  isShowLeftBtn.value = false
  isShowRightBtn.value = false
})

const scrollLeft = () => {
  toolbarRef.value.scrollTo({
    left: toolbarRef.value.scrollLeft - toolbarRef.value.clientWidth,
    behavior: 'smooth'
  });
}

const scrollRight = () => {
  toolbarRef.value.scrollTo({
    left: toolbarRef.value.scrollLeft + toolbarRef.value.clientWidth,
    behavior: 'smooth'
  });
}

const handleScroll = (e) => {
  isShowLeftBtn.value = e.target.scrollLeft > 0 ? true : false
  isShowRightBtn.value = e.target.scrollLeft + e.target.clientWidth < e.target.scrollWidth - 1 ? true : false
}

const handleFile = (evt) => {
  let file = evt.target.files[0]
  if (!file) return

  if (file && file.size > 2 * 1024 * 1024) {
    window.$message.error(instance.$t('signatures.uploadError'), {
      duration: 5000,
      icon: () => h('img', { src: MessageError })
    })
    evt.target.value = ''
    return
  }

  if (toolMode.value === 'annotation') {
    useDocument.setToolState('image')
    core.handleCreateStatus({
      bool: true,
      fileData: file
    })
  }

  if (activeTool.value !== 'image') return

  const reader = new FileReader()
  reader.onload = function (e) {
    const image = new Image()
    image.onload = function () {
      const data = {
        imageBase64: e.target.result,
        width: image.width,
        height: image.height,
        pageNum: currentPage.value
      }
      core.addAnnotationImage(data)
    }
    image.onerror = function (error) {
      console.log(error)
    }
    image.src = e.target.result
  }
  reader.onerror = function (error) {
    console.log(error)
  }
  reader.readAsDataURL(file)
}

const clickUpload = () => {
  useDocument.setToolState('image')
}
</script>

<style lang="scss" scoped>
.toolbar {
  display: flex;
  position: relative;
  width: 100%;
  height: 44px;
  z-index: 4;
  background-color: var(--c-toolbar-bg);
  border-bottom: 1px solid var(--c-toolbar-border);
  opacity: 1;

  &.hidden {
    display: none;
  }

  &.disabled {
    opacity: 0.5;
    pointer-events: none;
  }

  .tools {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow-x: auto;
    overflow-y: hidden;
  }

  .scroll-container {
    display: flex;
    align-items: center;
    position: absolute;
    top: 0;
    bottom: 0;
    z-index: 1;
    pointer-events: none;
    width: 60px;
    background: var(--c-toolbar-bg);

    &.left {
      left: 0;
      mask-image: -webkit-gradient(linear, right top, left top, from(transparent), to(#000), color-stop(.5, #000));
      -webkit-mask-image: -webkit-gradient(linear, right top, left top, from(transparent), to(#000), color-stop(.5, #000));
      justify-content: flex-start;

      .flip-button {
        margin-left: 10px;
      }
    }

    &.right {
      right: 0;
      mask-image: -webkit-gradient(linear, left top, right top, from(transparent), to(#000), color-stop(.5, #000));
      -webkit-mask-image: -webkit-gradient(linear, left top, right top, from(transparent), to(#000), color-stop(.5, #000));
      justify-content: flex-end;

      .flip-button {
        margin-right: 10px;
      }
    }

    .flip-button {
      pointer-events: all;
      color: rgba(153, 153, 153, 1);

      &.button:not(.disabled):active {
        background-color: unset;
      }
    }
  }
}

@media screen and (max-width: 672px) {
  .toolbar {
    &.security,
    &.editor {

      .tools {
        justify-content: center;
      }
    }
    
    .tools {
      padding: 0 16px;
      justify-content: flex-start;
    }
  }
}
</style>
