<template>
    <div>
        <img
            v-if="image"
            :class="classes"
            :src="imageObject.data.attributes.path"
            ref="image"
            :alt="alt">
    </div>
</template>

<script>
    import Dropzone from 'dropzone'
    import { mapGetters } from 'vuex'

    export default {
        name: "UploadableImage",
        props: {
            imageWidth: {
                type: Number,
                required: true,
            },
            imageHeight: {
                type: Number,
                required: true,
            },
            location: {
                type: String,
                required: true
            },
            image: {
                type: Object,
                default: null,
            },
            author: {
                type: Object,
                required: true
            },
            id: {
                type: Number,
                required: true
            },
            model: {
                type: String,
                required: true
            },
            classes: String,
            alt: String
        },
        data: () => {
            return {
                dropzone: null,
                dropImage: null,
            }
        },
        mounted() {
            if(this.authUser.data.user_id === this.author.data.user_id) {
                this.dropzone = new Dropzone(this.$refs.image, this.settings)
            }
        },
        computed: {
            ...mapGetters({
                authUser: 'authUser'
            }),
            settings() {
                let url = '/api/images/' + this.model + '/' + this.id
                return {
                    paramName: 'image',
                    url: url,
                    acceptedFiles: 'image/*',
                    params: {
                        'width': this.imageWidth,
                        'height': this.imageHeight,
                        'location': this.location,
                    },
                    headers: {
                        'X-CSRF-TOKEN': document.head.querySelector('meta[name=csrf-token]').content
                    },
                    success: (e, res) => {
                        this.dropImage = res
                    }
                }
            },
            imageObject() {
                return this.dropImage || this.image
            }
        }
    }
</script>
