<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"/>
  </div>
</template>

<script>

import { TextViewer, ImageViewer } from 'pankow-viewers';
import { createDirectoryModel } from '../models/DirectoryModel.js';
import { sanitize } from 'pankow/utils';

const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? import.meta.env.VITE_API_ORIGIN : window.location.origin;

export default {
  name: 'FileViewer',
  components: {
    ImageViewer,
    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.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>

<style scoped>

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

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

}

</style>
