<template>
    <div class="file-uploader">

        <div v-if="results" :class="['has-files', state]" :style="{minHeight: height + 'px'}">
            <ul class="list-unstyled">
                <li v-for="result in results">
                    <img :src="result"/>
                </li>
            </ul>
        </div>

        <div v-else :class="['no-files', state]" :style="{minHeight: height + 'px'}">

            <input class="input-file"
                   type="file"
                   :name="name"
                   :multiple="multiple"
                   @change="onFileChange"
            >

            <div v-if="!message" class="message">
                Drag your file{{ multiple ? '(s)' : '' }} here to begin<br> or click to browse
            </div>

            <div class="message" v-else>
                {{ message }}
            </div>
        </div>

    </div>
</template>


<script>
export default {
    props : {
        url : {
            required : true
        },
        name : {
            default : false
        },
        multiple : {
            default : false
        },
        height : {
            default : 180
        }
    },
    data() {
        return {
            message : '',
            state : 'ready',
            file : '',
            files : [],
            results : null
        }
    },
    methods : {
        onFileChange(e) {
            // Get the files if any
            this.files = e.target.files || e.dataTransfer.files;
            if (!this.files.length) {
                return;
            }

            // Notify the user that we are doing something
            this.message = "Uploading file(s) please wait...";
            this.state = 'uploading';

            // Create a new form data object and append the files to it
            let formData = new FormData();
            for (let i = 0; i < this.files.length; i++) {
                formData.append('files[]', this.files[i]);
            }

            // Upload to the server
            window.axios.post(this.url, formData)
                .then((response) => {
                    this.state = 'success';
                    this.results = response.data;
                    console.log(this.results);
                })
                .catch(e => {
                    this.state = 'error';
                    this.message = e.message;
                });
        },
    },
    mounted : function () {
        if (!this.url) {
            this.state = 'error';
            this.message = "Error: Please set the url attribute to manage the uploads..";
        }
    }
}
</script>
