<template>
  <div id="outerContainer" class="app" :class="{ dark: themeMode === 'Dark' }">
    <div v-show="!isHeaderDisabled">
      <Header />
    </div>
    <div
      class="content"
      ref="contentRef"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
    >
      <LeftPanel :isHeaderDisabled="isHeaderDisabled" />
      <DocumentContainer :isHeaderDisabled="isHeaderDisabled" />
      <CompareDocumentContainer />
      <DocumentEditorContainer v-if="toolMode === 'document'" :Sortable="Sortable" />
      <RightPanel :isHeaderDisabled="isHeaderDisabled" />
      <RightPanelPageMode :isHeaderDisabled="isHeaderDisabled" />
      <StampPanel :isHeaderDisabled="isHeaderDisabled" />
      <LinkPanel :isHeaderDisabled="isHeaderDisabled" />
      <ContentEditorPanel :isHeaderDisabled="isHeaderDisabled" />
    </div>
    <div class="mask" :class="{ active: downloading || downloadError !== '' }">
      <div v-show="downloading" class="loading"><Loading /></div>
      <div v-show="downloadError !== ''" class="error-dialog">
        <div class="close-btn">
          <Button @click="closeMask">
            <Close />
          </Button>
        </div>
        <div class="fail-logo"><Failed /></div>
        <div class="text">{{ downloadError }} failed</div>
        <div class="confirm-btn" @click="closeMask">OK</div>
      </div>
    </div>
    <div class="mask active" v-show="activeSignCreatePanel"><SignCreatePanel /></div>
  </div>
  <div id="printContainer"></div>
  <Message />
</template>

<script setup>
import initDocument from '@/helpers/initDocument'
import getHashParameters from '@/helpers/getHashParameters'
import { ref, computed, provide, getCurrentInstance } from 'vue'
import { useViewerStore } from '@/stores/modules/viewer'
import { Sortable, MultiDrag } from 'sortablejs'
import core from '@/core'

Sortable.mount(new MultiDrag())

const useViewer = useViewerStore()
const themeMode = computed(() => useViewer.getThemeMode)
const downloading = computed(() => useViewer.getDownloading)
const downloadError = computed(() => useViewer.getDownloadError)
const activeSignCreatePanel = computed(() => useViewer.isElementOpen('signCreatePanel'))
const activeDigitalSignCreatePanel = computed(() => useViewer.isElementOpen('digitalSignCreatePanel'))
const popoverChanged = computed(() => useViewer.getPopoverChanged)
const toolMode = computed(() => useViewer.getToolMode)
const scaleValue = computed(() => useViewer.getScale)


const instance = getCurrentInstance().appContext.app.config.globalProperties

provide('themeMode', themeMode)
initDocument({ $t: instance.$t })
const toolBarDisabled = !getHashParameters('header', true)
if (toolBarDisabled) {
  useViewer.setDisabledElements('header')
}

const isHeaderDisabled = computed(() => useViewer.getDisabledElements('header'))

window.instance.changeFile = () => {
  const openFileInput = document.getElementById("fileInput")
  openFileInput.click()

  if (activeSignCreatePanel.value || activeDigitalSignCreatePanel.value) {
    useViewer.closeElement('signCreatePanel')
    useViewer.closeElement('digitalSignCreatePanel')
    useViewer.setActiveToolMode('view')
  }
  if (!popoverChanged.value) useViewer.setPopoverChanged(true)
  if (toolMode.value === 'document') core.saveDocumentEdit('cancel')
}

const closeMask = () => {
  useViewer.setDownloadError('')
}

const contentRef = ref()
const scale = ref(1)
let initialDistance = 0
let initialScale = 1
let initialCurrentScale = 1
let newScale = 0
let isScaling = false

const onTouchStart = (event) => {
  if (event.touches.length === 2) {
    initialDistance = calculateDistance(event.touches)
    initialScale = scale.value
    initialCurrentScale = scaleValue.value
    newScale = initialCurrentScale
    isScaling = true
  }
}

const onTouchMove = (event) => {
  if (isScaling && event.touches.length === 2) {
    contentRef.value.style.transform = `scale(${scale.value})`
    const newDistance = calculateDistance(event.touches)
    scale.value = initialScale * (newDistance / initialDistance)
    newScale = Math.round(initialCurrentScale * scale.value)
    useViewer.setCurrentScale(newScale / 100)
  }
}

const onTouchEnd = (event) => {
  if (isScaling && event.touches.length < 2) {
    contentRef.value.style.transform = ''
    core.scaleChanged(newScale / 100)
    scale.value = 1
    isScaling = false
  }
}

const calculateDistance = (touches) => {
  const dx = touches[0].clientX - touches[1].clientX
  const dy = touches[0].clientY - touches[1].clientY
  return Math.sqrt(dx * dx + dy * dy)
}
</script>

<style lang="scss">
  .dark {
    .loading {
      color: #FFF;
    }
    .form-container span {
      color: #FFF;
    }
    .findbar {
      background-color: #343A40;
    }
    .thumbnail .box-thumbnail {
      color: #FFF;
    }
    .print-dialog .print-container {
      background-color: #000;
      color: #FFF;
    }
    .outline-view, .layer-view {
      .treeItem {
        .title {
          &:hover {
            background-color: rgba(255, 255, 255, 0.1);
          }
          &.selected {
            background-color: rgba(255, 255, 255, 0.2);
          }
          .treeItemToggler {
            color: #FFF;
          }
        }
        .title a, > a {
          color: #FFF;
        }
        &:hover > a {
          background-color: rgba(255, 255, 255, 0.1);
        }
        &.selected > a {
          background-color: rgba(255, 255, 255, 0.2);
        }
      }
    }
    &#outerContainer .drop-down {
      background-color: #343A40;
      color: #FFF;
    }
    &#outerContainer .drop-item {
      &:hover {
        background-color: rgba(255, 255, 255, 0.1);
      }
      &.active {
        background-color: rgba(255, 255, 255, 0.2);
      }
    }
    .measure-pop {
      background-color: #000;
      div {
        color: #FFF;
      }
    }
  }
 .app {
    display: flex;
    flex-direction: column;
    position: relative;
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    -webkit-font-smoothing: antialiased;
    overflow: hidden;
  }
  .content {
    display: flex;
    flex-direction: row;
    flex: 1;
    overflow: auto;
    transform-origin: center center;
  }
  .divider {
    width: 1px;
    height: 20px;
    margin-right: 8px;
    background-color: var(--c-divider);
    flex-shrink: 0;
  }
  .mask {
    display: none;
    position: fixed;
    z-index: 999;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.3);
    text-align: center;
    .loading svg {
      animation: spin .8s linear infinite;
    }
    .close-btn .button {
      margin-left: auto;
      margin-right: 0;
    }
    &.active {
      display: flex;
    }
    .error-dialog {
      width: 100%;
      max-width: 284px;
      color: #232A40;
      padding: 16px 16px 40px;
      background: #FFFFFF;
      box-shadow: 0px 4px 32px var(--c-doc-editor-popup-shadow);
      border-radius: 4px;
      .fail-logo svg {
        width: 60px;
        height: 60px;
        margin-top: 12px;
        margin-bottom: 16px;
      }
      .text {
        font-size: 16px;
        line-height: 20px;
        color: #232A40;
      }
      .confirm-btn {
        width: 100%;
        max-width: 220px;
        margin: 30px auto 0;
        padding: 12px 0;
        color: #FFFFFF;
        background-color: #1460F3;
        border-radius: 6px;
        display: flex;
        align-items: center;
        font-weight: 700;
        font-size: 14px;
        line-height: 16px;
        justify-content: center;
      }
    }
  }
</style>
