<template>
    <div class="inline-file-selector relative">
        <loading-component  v-show="isLoading"></loading-component>
        <div class="row align-items-center justify-content-center b-a b-grey btn-rounded m-t-10 m-b-10 selector pointer" @click="$refs.fileInput.click()" :class="{hide: isPreview}" >
            <div class="col">
                <i class="fa fa-cloud-upload text-complete fs-18 m-r-5 inline v-align-middle lh-14"></i>
                <span class="muted fs-9 inline v-align-middle">click here to upload your file (max 2MB)</span>
            </div>
            <div class="col-auto">
                <div class="b-l b-grey btn-rounded pull-right bold text-complete all-caps fs-11 p-l-15 p-r-15 p-t-10 p-b-10"><i class="fa fa-plus m-r-5"></i>Select files</div>
            </div>
        </div>
        <div class="row">
            <div class="col no-padding">
                <div v-for="(file, index) in files" v-bind:key="index" class="row align-items-center justify-content-center b-a b-grey m-t-10 m-b-10 preview" :class="{hide: !isPreview}" >
                    <div class="col-auto p-r-0">
                        <div class="no-margin image-container" v-bind:style="{ 'background-image': 'url(' + file.thumbnail + ')' }">
                            <a v-bind:href="file.data" class="text-white full-width full-height text-center overlay-preview" ref="singleLightBox">
                                <i class="fa fa-search fs-20 hint-text lh-50"></i>
                            </a>
                        </div>
                    </div>
                    <div class="col">
                        <span class="muted fs-9 inline v-align-middle">{{file.name}}</span>
                    </div>
                    <div class="col-auto">
                        <div class="b-l b-grey pull-right bold muted all-caps fs-11 p-l-15 p-r-15 p-t-10 p-b-10 lh-100"><i class="fa fa-times fs-14 pointer" @click="removeFile(index)"></i></div>
                    </div>
                </div>
                <div v-if="multiple" class="row m-b-10" :class="{hide: !isPreview}">
                    <div class="col no-padding">
                        <div @click="$refs.fileInput.click()" class="b-a b-grey btn-rounded pull-right bold text-complete all-caps fs-11 p-l-15 p-r-15 p-t-5 p-b-5 pointer"><i class="fa fa-plus m-r-5"></i>Add files</div>
                    </div>
                </div>
            </div>
        </div>
        <input type="file" class="hide" ref="fileInput" v-on:change="onFileChange($event)" accept="image/*,.pdf,.xlsx" :multiple="multiple">
    </div>
</template>
<script>
    export default {
        props: {
            'data': {
                type: Array,
                default: []
            },
            'multiple': {
                type: Boolean,
                default: false
            },
            'allowed': {
                type: Array,
                default: function () {
                    return ['images', 'pdf', 'xlsx']
                }
            }
        },
		data() {
            return {
                files: [],
                validExtensions: this.allowed,
                isLoading: false,
				isPreview: false
            }
        },
        created() {
            let vm = this;
            if(this.data.length){
                $.map(this.data, function(obj){
                    vm.files.push({
                        thumbnail: vm.imageThumbnail(obj.name, 'storage/'+obj.location+'/'+obj.name),
                        name: vm.truncate(obj.name, 20),
                        data: 'storage/'+obj.location+'/'+obj.name
                    });
                });
                this.isPreview = true;
            }
        },
		methods: {
			removeFile(index){

                this.isLoading = true;

                this.files.splice(index,1);

                if(!this.files.length) {
                    this.isPreview = false;
                }

                this.updateChanges();

                this.isLoading = false;

			},
			onFileChange(event) {
			    let vm = this;
				let files = event.target.files || event.dataTransfer.files;

                if (files.length){

                    $.map(files, function(obj){

                        if(vm.validate(obj)){

                            vm.createFile(obj);
                            vm.isPreview = true;
                            vm.updateChanges();

                        }
                    });

				}
            },
            createFile(file) {

                let reader = new FileReader();

                this.isLoading = true;

                reader.onload = (e) => {

                    if(!this.fileExists(e.target.result)){

                        this.files.push({
                            thumbnail: this.imageThumbnail(file.name, e.target.result),
                            name: this.truncate(file.name, 20),
                            data: e.target.result
                        });

                        this.updateChanges();
                    }

                    this.isLoading = false;

                };

                reader.readAsDataURL(file);

            },
            imageThumbnail(fileName, data){
                switch(this.getExtensions(fileName)){
                    case 'xlsx':
                        return route('login')+"images/icons/xlsx.png";

                    case 'pdf':
                        return route('login')+"images/icons/pdf.png";

                    default:
                        return data;
                }
            },
            getValidExtensions(){
			    return $.map(this.validExtensions, function(value){
                    switch (value){
                        case 'images':
                            return ['jpg', 'svg', 'jpeg', 'png', 'bmp', 'gif'];
                        case 'pdf':
                            return 'pdf';
                        case 'xlsx':
                            return 'xlsx';
                    }
                });

            },
            validate(file){
                return ($.inArray(this.getExtensions(file.name), this.getValidExtensions()) !== -1);
            },
            getExtensions(fileName){
			    return fileName.split('.').pop();
            },
            updateChanges(){
                this.$emit('changeFile',  $.map(this.files, function(obj){
                    return obj.data;
                }));
            },
            fileExists(data){
                for(let i = 0; i < this.files.length; i++) {
                    if (this.files[i].data === data) {
                        return true
                    }
                }
                return false;
            },
            truncate(n, len) {
                let ext = n.substring(n.lastIndexOf(".") + 1, n.length).toLowerCase();
                let filename = n.replace('.' + ext,'');
                if(filename.length <= len) {
                    return n;
                }
                filename = filename.substr(0, len) + (n.length > len ? '[...]' : '');
                return filename + '.' + ext;
            }
        }
    }
</script>
