<template>
    <div class="row parentContainer">
        <div class="col">
            <div class="requestModal pointer" @click="loadFile" data-type="filePreview">
                <slot name="button" ></slot>
            </div>
            <modal-component styleType="fill-in" type="filePreview">
                <loading-component style="height: 200px; top: 0;" key="1" color="success" v-show="isLoading"></loading-component>
                <div class="row">
                    <div class="col text-center">
                        <img :src="src" class="w-100" v-if="type !== 'pdf'">
                        <iframe v-if="type === 'pdf'" class="pdf-display w-100 scrollable" style="height: 80vh" :src="'data:application/pdf;base64,'+src"></iframe>
                    </div>
                </div>
            </modal-component>
        </div>
    </div>
</template>

<script>
    export default {
        props: {
            file: {
                type: Object,
                required: true
            },
        },
        data(){
            return {
                isLoading: false,
                loaded: false,
                src: ''
            }
        },
        computed: {
            type() {
                return this.file.file.mime_type === 'application/pdf' ? 'pdf' : 'image'
            }
        },
        methods:{
            loadFile(){
                if(!this.loaded) {
                    this.isLoading = true;
                    let filePath = this.type === 'pdf' ? this.file.file.file_info.original.file : this.file.file.file_info[0].original.file;
                    this.submit(this.route('api.storage.document.file', filePath)+'/', 'get', 'imagePreviewSection', false, false)
                }
            },
            renderPdf() {
                this.isLoading = false;
            },
            successHandler(response){
                this.loaded = true;
                this.src = response.payload.src;
                this.isLoading = false;

                if(this.type === 'pdf'){
                    this.renderPdf()
                }
            },
            errorHandler(error, statusCode){
                this.src = statusCode === 404 ? '/images/3231370.jpg' : '/images/2942005.jpg'
                this.isLoading = false;
            }
        },

    }
</script>

<style scoped>

</style>