<template>
<div class="fileInputWrapper">
    <div class="fileUploadButton">
        {{title}}
        <input type="file" :id="id" :name="`${id}[]`" :accept="fileTypes" :multiple="multiple" @change="gatherFiles" ref="fileInput"/>
    </div>
    <div class="fileNames" v-show="showFileName">
        {{fileNames}}
    </div>
</div>

</template>

<script>
import { map, isString, toLower, isEmpty } from 'lodash'
export default {
    name: 'FileInput',
    props: {
        id: {
            type: String,
            required: true
        },
        title: {
            type: String,
            default: 'Choose file'
        },
        fileTypes: {
            type: String,
            default: '*'
        },
        multiple: {
            type: Boolean,
            default: false
        },
        showFileName: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            files: []
        }
    },
    computed: {
        fileNames () {
            return isEmpty(this.files) ? 'No file chosen' : map(this.files, 'name').join(', ')
        }
    },
    methods: {
        gatherFiles (e) {
            this.files = this.$refs.fileInput.files
            this.$emit('change', e)
            this.$emit('files', this.files)
        }
    },
    mounted () {
        this.$events.on(`fileinput|${this.id}`, (e) => {
            if (isString(e) && ['clear', 'reset'].includes(toLower(e))) {
                this.files = []
                this.$refs.fileInput.value = null
            } else if (e.task.toLowerCase() == 'clear') {
                this.files = []
                this.$refs.fileInput.value = null
            }
        })
    },
    beforeDestroy () {
        this.$events.off(`fileinput|${this.id}`)
    }
}
</script>
