
<template>
  <div>
    <div>
      <div>
        <input type="submit"
               class="button button-primary"
               value="Create directory"
               @click="openCreateDirectory()"/>

        <input type="submit"
               class="button button-primary"
               value="Toggle directory settings"
               @click="toggleDirectorySettings()"
               v-if="showDirectorySettingsButton()"/>
      </div>

      <div class="fotkipress-dir-path">
        Path: <dir-path :path="directoryPath"/>
      </div>

      <div v-if="directoryErrors.length > 0" class="error">
        <p v-for="error in directoryErrors">{{error}}</p>
      </div>

      <div class="fotkipress-files-container-wrapper"
           @dragover="uploadingFilesDragOver()"
           @dragend="uploadingFilesDragEnd()"
           v-infinite-scroll="loadMoreFiles"
           infinite-scroll-disabled="isLoadingMoreDirectoryFiles">
        <directory-tree :path="directoryPath"/>

        <div class="fotkipress-files-section">
          <div v-if="showLayout" class="fotkipress-layout" v-bind:style="{height: height + 'px', width: width + 'px'}"></div>

          <create-directory-window :visible="showCreateDirectory"
                                   :errors="createDirectoryErrors"
                                   :onsubmit="createDirectory"
                                   :oncancel="cancelCreateDirectory"/>

          <uploading-window :visible="showUploadingWindow"
                            :files="uploadingFiles"
                            :clear="clearModalWindow"
                            :close="closeModalWindow"/>

          <div v-if="onUploadingFileDragging"
               v-bind:style="{height: height + 'px', width: width + 'px'}"
               class="drop-area-layout"></div>

          <input type="file"
                 name="files"
                 v-if="onUploadingFileDragging"
                 @click="uploadingFilesClick($event)"
                 @change="uploadingFilesChange($event, directoryPath)"
                 @drop="uploadingFilesDragLeave()"
                 @dragleave="uploadingFilesDragEnd()"
                 @dragend="uploadingFilesDragEnd()"
                 class="drop-area-input"
                 v-bind:style="{height: height + 'px', width: width + 'px'}"
                 multiple>

          <shortcode-instructions :visible="showShortcodeInstructions()"
                                  :username="username"
                                  :isadmin="isadmin"
                                  :path="getShortcodePath()"/>

          <div class="fotkipress-files-container">
            <div v-for="file in directoryFiles"
                 class="fotkipress-file"
                 @dragstart="localFileStartDrag(file)"
                 @dragenter="localFileOverFile($event, file)"
                 @dragover="localFileOverFile($event, file)"
                 @dragleave="localFileLeaveDrag()"
                 @dragend="localFileEndDrag()"
                 @drop="localFileDrop(file)"
                 v-bind:class="{
                     'fotkipress-directory-component-dragged': localFileDragged(file),
                     'fotkipress-directory-component-drag-over': localFileDraggedOver(file)
                     }">

              <directory v-if="file.isdir"
                         :name="file.name"
                         :path="file.path"
                         :ispublic="file.ispublic"
                         :isreadable="file.isreadable"/>

              <file v-if="!file.isdir"
                    :file="file"
                    :isloading="file.isloading"/>
            </div>

            <div v-if="showInfoMessage()" class="fotkipress-file-info-message">
              <span>
                No files in this directory.
                Drag and drop files here.
              </span>
            </div>
          </div>
        </div>

        <directory-settings v-if="showDirectorySettings()" :path="path"/>
      </div>
    </div>
  </div>
</template>


<script>
import {mapGetters} from 'vuex';

import API from './../../api';


export default {
    props: {
        username: {
            type: String,
            required: true
        },
        isadmin: {
            type: Boolean,
            required: true
        }
    },

    data() {
        return {
            height: 0,
            width: 0,

            onUploadingFileDragging: false,

            files: [],

            errors: [],

            showLayout: false,

            showUploadingWindow: false,
            showCreateDirectory: false,
            createDirectoryErrors: [],

            isDirectorySettingsVisible: false
        };
    },

    computed: mapGetters({
        directoryPath: 'directoryPath',
        directoryFiles: 'directoryFiles',
        directoryFilesOffset: 'directoryFilesOffset',
        isLoadingMoreDirectoryFiles: 'isLoadingMoreDirectoryFiles',

        uploadingFiles: 'uploadingFiles',

        directoryErrors: 'directoryErrors',

        draggedSrcFilePath: 'draggedSrcFilePath',
        draggedDstFilePath: 'draggedDstFilePath'
    }),

    created() {
        var path = this.getPath();

        if (path) {
            this.$store.dispatch('getFiles', {path});
        } else {
            this.$store.dispatch('getRootFiles');
        }
    },

    updated() {
        var files = this.$el.getElementsByClassName('fotkipress-files-section')[0];
        this.height = files.clientHeight;
        this.width = files.clientWidth;
    },

    watch: {
        '$route'(to, from) {
            if (to.path === '/' || to.path === '/browser/') {
                this.$store.dispatch('getRootFiles');
                this.closeDirectorySettings();
                return;
            }

            if (to.path.indexOf('/browser/') !== 0) {
                return;
            }

            var toPath = decodeURIComponent(to.path.slice('/browser/'.length));
            this.$store.dispatch('getFiles', {path: toPath});
        }
    },

    methods: {
        getPath() {
            var path = '';

            if (Object.keys(this.$route.params).length > 0) {
                var path = this.$route.params[0];
            }

            return path;
        },

        /* --- */

        showShortcodeInstructions() {
            if (this.directoryPath === 'public') {
                return true;
            }

            return this.directoryPath.indexOf('public/') == 0;
        },

        getShortcodePath() {
            return decodeURIComponent(this.directoryPath.slice('public/'.length));
        },

        showInfoMessage() {
            if (this.directoryFiles.length !== 1) {
                return false;
            }

            if (this.directoryPath === '') {
                return this.directoryFiles.length === 1 && this.directoryFiles[0].name === 'public';
            }

            return this.directoryFiles.length === 1 && this.directoryFiles[0].name === '..';
        },

        /* --- */

        loadMoreFiles() {
            if (this.directoryFiles.length === 0) {
                return;
            }

            this.$store.dispatch('getMoreFiles', {path: this.directoryPath});
        },

        /* --- */

        uploadingFilesDragOver() {
            if (this.draggedSrcFilePath) {
                return;
            }

            this.onUploadingFileDragging = true;
        },

        uploadingFilesDragLeave() {
            this.onUploadingFileDragging = false;
        },

        uploadingFilesDragEnd() {
            this.onUploadingFileDragging = false;
        },

        uploadingFilesClick(evt) {
            evt.preventDefault();
        },

        uploadingFilesChange(evt, path) {
            var files = evt.target.files;

            if (!files.length) {
                return;
            }

            var formDataFiles = [];

            for (var i = 0; i < files.length; i++) {
                var file = files[i];

                if (!this.isFileUploading(path, file)) {
                    formDataFiles.push(file);
                }
            }

            if (formDataFiles.length === 0) {
                return;
            }

            this.showUploadingWindow = true;

            for (var i = 0; i < formDataFiles.length; i++) {
                var file = formDataFiles[i];
                this.uploadFile(path, file);
            }
        },

        uploadFile(path, file) {
            this.showUploadingWindow = true;
            this.$store.dispatch('uploadFile', {path, file});
        },

        isFileUploading(path, file) {
            for (var i in this.uploadingFiles) {
                var uFile = this.uploadingFiles[i];

                if (uFile.name === file.name && uFile.dirPath === path && uFile.status === 'UPLOADING') {
                    return true;
                }
            }

            return false;
        },

        /* --- */

        clearModalWindow() {
            this.$store.dispatch('clearUploadingFiles');
        },

        closeModalWindow() {
            this.showUploadingWindow = false;
            this.clearModalWindow();
        },

        /* --- */

        localFileStartDrag(file) {
            this.$store.dispatch('setDraggedSrcFilePath', {path: file.path});
        },

        localFileOverFile(evt, file) {
            evt.preventDefault();

            if (!file.isdir) {
                return;
            }

            if (file.ispublic && file.path !== 'public') {
                return;
            }

            this.$store.dispatch('setDraggedDstFilePath', {path: file.path});
        },

        localFileLeaveDrag() {
            this.$store.dispatch('unsetDraggedDstFilePath');
        },

        localFileEndDrag() {
            this.$store.dispatch('unsetDraggedSrcFilePath');
            this.$store.dispatch('unsetDraggedDstFilePath');
        },

        localFileDrop(file) {
            if (file.ispublic && file.path !== 'public') {
                return;
            }

            var fileSource = this.draggedSrcFilePath;
            var fileDestination = file.path;

            if (fileSource !== null && fileSource !== fileDestination) {
                this.$store.dispatch('moveFile', {fileSource, fileDestination}).then((file) => {
                    if (file && file.isdir) {
                        this.$store.dispatch('handleDirectoryTreeChanges', {fileSource, fileDestination, file});
                    }
                }).catch((errors) => {
                    this.$store.dispatch('setTempErrors', {errors});
                });
            }
        },

        localFileDragged(file) {
            return file.path === this.draggedSrcFilePath;
        },

        localFileDraggedOver(file) {
            if (!file.isdir || (file.ispublic && file.path !== 'public')) {
                return false;
            }

            return file.path === this.draggedDstFilePath && file.path !== this.draggedSrcFilePath;
        },

        /* --- */

        openCreateDirectory() {
            this.showLayout = true;
            this.showCreateDirectory = true;
        },

        createDirectory(directoryName) {
            var directoryPath = this.directoryPath;

            this.$store.dispatch('createDirectory', {directoryPath, directoryName}).then(() => {
                this.showLayout = false;
                this.showCreateDirectory = false;
                this.createDirectoryErrors = [];

                this.$store.dispatch('updateDirectoryTreeIfPathExists', {path: directoryPath});
            }).catch((errors) => {
                this.createDirectoryErrors = errors;
            });
        },

        cancelCreateDirectory() {
            this.showLayout = false;
            this.showCreateDirectory = false;
            this.createDirectoryErrors = [];
        },

        /* --- */

        showDirectorySettingsButton() {
            return this.directoryPath !== '' && this.directoryPath.indexOf('public') !== 0;
        },

        toggleDirectorySettings() {
            this.isDirectorySettingsVisible = !this.isDirectorySettingsVisible;
        },

        closeDirectorySettings() {
            this.isDirectorySettingsVisible = false;
        },

        showDirectorySettings() {
            return this.isDirectorySettingsVisible;
        }
    }
}
</script>
