<template>
<transition name="fade" appear>
    <div class="modal fade show modal-overlay" :class="{ 'show-modal' : modalActive == true}" role="dialog" tabindex="-1"  v-show="modalActive">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content" v-if="!viewLoading">
                <div class="modal-header">
                    <h5 class="text-dark mb-0" id="file_browser_modal_header">{{title}}</h5>
                    <button @click="cancelModal" type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body" id="file_browser_modal_body" style="padding-bottom: 0px;">
                    <div style="font-size: 12px;font-weight: bold; float:left; cursor: pointer; padding: 0 5px">
                            <span @click="createFolder" aria-hidden="true">
                                <i class="fa fa-folder color-folder"></i> Create Folder
                            </span>
                        
                    </div>
                    <div style="font-size: 12px;font-weight: bold; float:left; cursor: pointer; padding: 0 5px">
                        <UploadFile @update:isEditing="isEditing = $event" label="Upload File" id='upload-file' @update:endUpload="endUploadFile" @startUpload="startUploadFile" :path="currentPath"></UploadFile>
                    </div>
                    <div style="clear: both"></div>
                        
                    <ul class="list-group" id="lgItems" style="max-height: 240px;overflow: scroll;-webkit-overflow-scrolling: touch;height: 180px;border: 1px solid #f1f1f1;margin-bottom: 10px;">
                        <li v-if="showNewCreateFolder">
                            <div  style="float:left"><input class="input-new-folder" v-model="newFolder" /></div>
                            <div style="float:left; padding-left:5px; font-size:12px">
                                <button class='close' @click="saveNewFolder" type="button" style="font-size: 17px !important; padding-top:4px"  aria-label="Close"><span aria-hidden="true"><i class="fa fa-floppy-o"></i></span>
                                </button>
                            </div>
                            <div style="float:left; padding-left:5px; font-size:12px">
                                <button @click="cancelCreateFolder" type="button" class="close" style="font-size: 17px !important; padding-top:4px" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                                </button>
                            </div>
                            <div style="clear:both"></div>
                        </li>
                        <li v-for="(content, index) in fileList" :key="index" @click="fileBrowserSelected(index)" @dblclick='doubleClick(index)' class="list-group-item fileItem"  path="dir_path">
                            <a class="list-group-item list-group-item-action" :class="[content.selected ? 'selectedItem' : 'unselectedItem' ]" style="border-style: none;padding: 4px;padding-left: 20px;">
                            <span style="padding-right: 8px;">
                            <i class="fa" :class="{
                                'fa-folder color-folder' : content.type === 'dir',
                                'fa-file color-file'  : content.type === 'file',
                                'fa-level-up color-level-up'  : content.type ==='up_dir'
                            }" :label="content.name" :type="content.type" >
                            </i>
                            </span>
                            <span :type="content.type" style="font-size: 12px;font-weight: bold;">
                                <span v-if="content.type === 'up_dir'">...</span>
                                <span v-else>{{content.name}}</span>
                            </span>
                            </a>
                        </li>
                    </ul>
                    <div class="table-responsive table-borderless" style="border-style: none;border-bottom: 1px none #e3e6f0 ;">
                        <table class="table table-sm">
                            <tbody>
                                <tr>
                                    <td class="align-middle" style="width: 100px;font-size: 14px;">File Path<br></td>
                                    <td class="align-middle">
                                        <input type="text" id="txtFileExpPath" class="form-control-sm form-control" style="background: #ffffff00;border-radius: 0px;border-style: none;border-bottom-style: dashed;" :readonly="readonly" v-model="nameFileSelected">
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button @click="cancelModal" class="btn btn-dark" type="button" data-dismiss="modal" style="background: #5d6270;">Cancel</button>
                    <button class="btn" id="btn_select_modal" type="button" style="background: #769b76;color: #ffffff;" @click="okModal">Select</button>
                </div>
            </div>
            <div class="modal-content" v-if="viewLoading">
                <div class="modal-header">
                    <h5 class="text-dark mb-0" id="file_browser_modal_header">{{title}}</h5>
                </div>
                <div class="modal-body" id="file_browser_modal_body" style="padding-bottom: 0px;height: 380px">
                    <div class="col text-center"><span class="spinner-border spinner-border-sm align-top" role="status" id="spn_card_connections" v-show="load"></span> Uploading file...</div>
                </div>
            </div>
        </div>
    </div>
    
</transition>
</template>
<script lang="ts">
import { DirectoryFilesService } from '@/domain/services/DirectoryFiles.service'
import { DirectoryFilesResponse } from '@/domain/models/directories/DirectoryFilesResponse.interface'
import { Content } from '@/domain/models/directories/Content.interface'
import { FileItem } from '@/lib-components/component/InputFileBrowser/model/FileItem.class';
import  UploadFile  from '@/lib-components/component/UploadFile.vue';
import { Response } from '@/domain/models/Response.interface';
import useVuelidate from '@vuelidate/core';
import { required } from '@vuelidate/validators'

export default {
     setup () {
        return { v$: useVuelidate() }
    },
    props: {
        title: String,
        text: String,
        modalActive:Boolean,
        pathNameCurrent:String,
        typeSelect: { type: String, default: 'file' },
        multipleFileSeparator: { type: String, default: '|' },
        readonly: { type: Boolean, default: true },
        resetFilePath : { type: Boolean, default: false, required: false }
    },
    validations () {
        return {
            newFolder: { required }
        }
    },
    components:{
        UploadFile
    },
    data: () => {
        return {
            load : true,
            viewLoading: false,
            fileList: [],
            directoryFilesService : {} as DirectoryFilesService,
            directoryFilesContent : {} as DirectoryFilesResponse,
            fileSelected : {} as Content,
            nameFileSelected :'',
            showNewCreateFolder: false,
            newFolder: '',
        }
    },
    async mounted(){
        this.directoryFilesService = new DirectoryFilesService();
    },
    async updated(){
        if(this.modalActive){
            await this.updateFileList("/");
        }
    },
    computed:{
        currentPath(){
            let path = (this.fileSelected === undefined)? '/' : this.fileSelected.path;
            return path;
        }
    },
    methods: {
            createFolder(){
                this.showNewCreateFolder = true;
            },
            saveNewFolder(){
                this.v$.$validate();
                if (!this.v$.$error){
                    this.viewLoading = true;
                     let path = (this.currentPath === undefined)? '/' : this.currentPath; 
                    let promise = this.directoryFilesService.createFolderToServer(path, this.newFolder);
                    promise.then((response: Response) => {
                        if(response.code == 200){
                            this.updateFileList(this.currentPath);
                        }
                        this.viewLoading = false;
                        this.showNewCreateFolder =false;
                    });
                }
                    
            },
            cancelCreateFolder(){
                this.showNewCreateFolder =false;
            },
            startUploadFile(){
                this.viewLoading = true;
            },
            endUploadFile(promise: any){
                promise.then((response: Response) => {
                    if(response.code == 200){
                        this.updateFileList(this.currentPath);
                    }
                    this.viewLoading = false;
                });
            },
            closeModal(){
                this.$emit("close");
                },
            cancelModal(){
                this.nameFileSelected = '';
                this.$emit("cancel");
                },
            okModal(){
                if(this.fileList.filter(item => item.selected).length > 0 || !this.readonly || (this.typeSelect === 'folder' && this.fileSelected.selected)){
                    this.$emit("selectFileBrowser", this.nameFileSelected);
                }
            },
            async updateFileList(path: String) {
                path =  (path === undefined)? '/' : path;
                this.directoryFilesContent = await this.directoryFilesService.getDirectoryListingFromServer(path);
                this.fileList = this.directoryFilesContent.contents.map(function(item: any){
                    let itemFile: FileItem;
                    itemFile =  new FileItem();
                    itemFile.path = item.path;
                    itemFile.name = item.name;
                    itemFile.type =  item.type
                    return itemFile;
                });
            },
            async doubleClick(indexSelected: number){
                if(this.typeSelect === 'folder'){
                    this.fileSelected =  this.fileList[indexSelected];
                    if(this.fileSelected.type == 'dir'){
                        this.fileList[indexSelected].selected =  true;
                        await this.updateFileList(this.fileSelected.path);
                    }
                }
            },
            async fileBrowserSelected(indexFileSelected: number)
            {
               
                this.fileSelected =  this.fileList[indexFileSelected];
                if(this.typeSelect === 'file' || this.typeSelect === 'folder'){
                    this.fileList = this.fileList.map(function(item){ item.selected = false; return item;});
                }
                if(((this.typeSelect === 'file' || this.typeSelect === 'list') && this.fileList[indexFileSelected].type === 'file') || (this.typeSelect === 'folder' && this.fileList[indexFileSelected].type === 'dir')){
                    this.fileList[indexFileSelected].selected =  !(this.fileList[indexFileSelected].selected);
                }

                if((this.fileSelected.type != 'file' && this.typeSelect !== 'folder' ) ||this.fileSelected.type == 'up_dir') {
                   await this.updateFileList(this.fileSelected.path);
                }

                await this.setSelection();
            },
            async setSelection(){
                this.nameFileSelected = await this.fileList.filter(item => item.selected)
                .map(function(item){ return item.path.slice(1); })
                .toString();
            }
        },
    watch: {
      resetFilePath( value : Boolean) {
        if(!value) return
        this.nameFileSelected = '';
      }
    }
}

</script>
<style scoped>
.color-file{
    color: #647894;
}
.color-folder{
    color:#cbcc62;
}
.color-level-up{
    color:#000000;
}
.show-modal
{
    display: block;
    padding-right: 17px;
}

.modal-overlay {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 98;
    background-color: rgba(0, 0, 0, 0.3);
}

.fade-enter-active,
.fade-leave-active {
 transition: opacity .5s;
}

.fade-enter,
.fade-leave-to {
 opacity: 0;
}

.slide-enter-active,
.slide-leave-active {
 transition: transform .5s;
}

.slide-enter,
.slide-leave-to {
 transform: translateY(-50%) translateX(100vw);
}

.fileItem{
    margin: 0px;
    margin-right: 0px;
    padding: 0px;
    border-style: none;
    padding-left: 0px;
    cursor: pointer;
}

.selectedItem{
    background: var(--selected-item-background) !important;
    color: var(--selected-item-color) !important;
}

.unselectedItem{
    background: var(--unselected-item-background);
    color: var(--unselected-item-color);
}
.input-new-folder{
    border: 1px solid rgba(0,0,0,.2);
    border-radius: 0.3rem;
    width: 398px;
    font-size: 12px;
    background-color: white !important;
}

.input-new-folder:focus {
    outline: none !important;
}

.botton{
    float: right;
    line-height: 1;
    text-shadow: 0 1px 0 #fff;
    opacity: .5;
}
</style>

