<script>

import { TextViewer, PdfViewer, ImageViewer } from '@cloudron/pankow/viewers';
import { API_ORIGIN } from '../constants.js';
import { createDirectoryModel } from '../models/DirectoryModel.js';
import { sanitize } from '@cloudron/pankow/utils';

export default {
  name: 'FileViewer',
  components: {
    ImageViewer,
    PdfViewer,
    TextViewer,
  },
  data() {
    return {
      resourceId: '',
      resourceType: '',
      item: null,
      active: ''
    };
  },
  methods: {
    onClose() {
      location.replace('#/home' + location.hash.slice('#/viewer'.length, location.hash.lastIndexOf('/')+1));
    },
    imageViewerNavigationHandler() {
      // nothing to do
    },
    async saveHandler(item, content) {
      await this.directoryModel.save(this.filePath, content);
    }
  },
  async mounted() {
    this.resourceId = this.$route.params.resourceId;
    this.resourceType = this.$route.params.type;

    this.filePath = this.$route.params.filePath.join('/');
    const fileName = this.$route.params.filePath[this.$route.params.filePath.length-1];
    const parentDirectoryPath = sanitize(this.filePath.split('/').slice(0, -1).join('/'));

    this.directoryModel = createDirectoryModel(API_ORIGIN, localStorage.token, (this.resourceType === 'volume' ? 'volumes/' : 'apps/') + this.resourceId);
    const files = await this.directoryModel.listFiles(parentDirectoryPath);

    this.item = files.find(i => i.fileName === fileName);

    if (!this.item) {
      console.log('File not found', this.filePath);
      return;
    }

    if (this.$refs.imageViewer.canHandle(this.item)) {
      // collect other files in directory for prev/next action
      const otherSupportedEntries = files.filter((item) => this.$refs.imageViewer.canHandle(item)).map((item) => {
        item.resourcePath = `/viewer/${this.resourceType}/${this.resourceId}${item.folderPath}/${item.fileName}`;
        item.fullFileUrl = this.directoryModel.getFileUrl(`${item.folderPath}/${item.fileName}`);
        return item;
      });

      this.$refs.imageViewer.open(this.item, otherSupportedEntries);
      this.active = 'imageViewer';
    } else if (this.$refs.pdfViewer.canHandle(this.item)) {
      const content = await this.directoryModel.getFile(this.filePath);
      this.item.fullFileUrl = this.directoryModel.getFileUrl(`${this.item.folderPath}/${this.item.fileName}`);
      this.$refs.pdfViewer.open(this.item, content);
      this.active = 'pdfViewer';
    } else if (this.$refs.textEditor.canHandle(this.item)) {
      const content = await this.directoryModel.getFile(this.filePath);
      this.$refs.textEditor.open(this.item, content);
      this.active = 'textEditor';
    } else {
      console.warn(`no editor or viewer found for ${this.item.mimeType}`, this.item);
      this.active = '';
      window.location.replace(this.directoryModel.getFileUrl(this.filePath));
    }
  }
};

</script>

<template>
  <div class="viewer">
    <TextViewer ref="textEditor"
      v-show="active === 'textEditor'"
      :save-handler="saveHandler"
      @close="onClose"
      :tr="$t"
    />
    <ImageViewer ref="imageViewer" v-show="active === 'imageViewer'" @close="onClose" :navigation-handler="imageViewerNavigationHandler"/>
    <PdfViewer ref="pdfViewer" v-show="active === 'pdfViewer'" @close="onClose"/>
  </div>
</template>

<style scoped>

.viewer{
  flex-grow: 1;
  overflow: hidden;
  height: 100%;
  display: flex;
}

.main-view-col {
  overflow: auto;
  flex-grow: 1;

}

</style>
