<template>
    <div id="ticketEditor">
        <h1>Ticket Editor</h1>
        <div class="toolbar">
            <router-link to="/admin/events/view" class="toolbar-item" title="Back to event settings">Back</router-link>
            <form class="toolbar-item">
                <input type="file" accept="application/pdf" id="pdfTemplate" class="toolbar-item">
            </form>
            <button @click="loadPDF();" class="toolbar-item">Load file</button>
            <button @click="saveTemplate()" class="toolbar-item" title="Save your ticket">Save Template</button>
        </div>
        <div id="editor">Loading editor...</div>
        <notifications ref="notification" location="topleft"></notifications>
    </div>
</template>

<script>
    import { Designer } from '@pdfme/ui';
    import notifications from '@/components/notifications/notifications.vue';

    export default {
        name: 'ticketEditor',
        data() {
            return {
                designer: null,
            }
        },
        components: {
            notifications
        },
        methods: {
            saveTemplate() {
                const saving = this.$refs.notification.createNotification( 'Saving...', 5, 'progress', 'normal' );
                let fetchOptions = {
                    method: 'post',
                    body: JSON.stringify( { 'location': sessionStorage.getItem( 'selectedTicket' ), 'data': this.designer.getTemplate() } ),
                    headers: {
                        'Content-Type': 'application/json',
                        'charset': 'utf-8'
                    }
                };

                fetch( '/admin/api/saveTickets', fetchOptions ).then( res => {
                    if ( res.status === 200 ) {
                        res.text().then( () => {
                            this.$refs.notification.cancelNotification( saving );
                            this.$refs.notification.createNotification( 'Saved successfully', 5, 'ok', 'normal' );
                        } );
                    }
                } );
            },
            loadPDF () {
                let files = document.getElementById( 'pdfTemplate' ).files;
                if ( files.length ) {
                    let pdfLoading = this.$refs.notification.createNotification( 'Loading pdf...', 5, 'progress', 'normal' );
                    let pdf = files[ 0 ];
                    if ( pdf.name.substring( pdf.name.length - 4 ) === '.pdf' ) {
                        let fileReader = new FileReader();
                        let base64;
                        let self = this;

                        // Onload of file read the file content
                        // https://stackoverflow.com/questions/13538832/convert-pdf-to-a-base64-encoded-string-in-javascript?rq=4

                        fileReader.onload = function( fileLoadedEvent ) {
                            base64 = fileLoadedEvent.target.result;
                            let oldTemplate = self.designer.getTemplate();
                            oldTemplate[ 'basePdf' ] = base64;
                            self.designer.updateTemplate( oldTemplate );
                            self.$refs.notification.cancelNotification( pdfLoading );
                            self.$refs.notification.createNotification( 'Loaded pdf successfully', 5, 'ok', 'normal' );
                        };
                        fileReader.readAsDataURL( pdf );
                    } else {
                        this.$refs.notification.createNotification( 'Cannot load pdf: Not a pdf!', 5, 'error', 'normal' );
                    }
                } else {
                    this.$refs.notification.createNotification( 'Cannot load pdf: No file selected', 5, 'error', 'normal' );
                }
            }
        },
        created() {
            setTimeout( () => {
                const domContainer = document.getElementById( 'editor' );
                fetch( '/admin/API/getTicketTemplate?ticket=' + sessionStorage.getItem( 'selectedTicket' ) ).then( res => {
                    const template = {
                        basePdf: "data:application/pdf;base64,[encoded data, 20696 characters]",
                        schemas: [
                            {
                                "locationAndTime":{
                                    "type":"text",
                                    "position":{"x":90,"y":70},
                                    "width":85,
                                    "height":10,
                                    "fontName":"Roboto"
                                },"eventName":{
                                    "type":"text",
                                    "position":{"x":89.7,"y":30},
                                    "width":85,
                                    "height":15,
                                    "alignment":"left",
                                    "fontSize":18,
                                    "characterSpacing":0,
                                    "lineHeight":1,
                                    "fontName":"Roboto"
                                },"ticketName":{
                                    "type":"text",
                                    "position":{"x":90,"y":55},
                                    "width":85,
                                    "height":10,
                                    "fontName":"Roboto",
                                    "alignment":"left"
                                },"ticketQRCode":{
                                    "type":"qrcode",
                                    "position":{"x":25,"y":30.05},
                                    "width":50,"height":50
                                }
                            }
                        ],
                        "columns":[
                            "locationAndTime",
                            "eventName",
                            "ticketName",
                            "ticketQRCode"
                        ],
                        "sampledata":[
                            {
                                "locationAndTime":"Time and date of event",
                                "eventName":"Your Event name will be filled in automatically",
                                "ticketName":"Ticket details go here (Ticket name)",
                                "ticketQRCode":"QR-Code for entry control will appear here"
                            }
                        ],
                    }
                    if ( res.status === 200 ) {
                        res.json().then( data => {
                            if ( Object.keys( data ) ) {
                                this.designer = new Designer( { domContainer, data } );
                            } else {
                                this.designer = new Designer( { domContainer, template } );
                            }
                        } ).catch( () => {
                            this.designer = new Designer( { domContainer, template } );
                        } );
                    } else {
                        this.designer = new Designer( { domContainer, template } );
                    }
                    // designer.updateTemplate(  ) -> Used to update the template AND base PDF
                } );
            }, 300 );
        }
    }
    </script>
    
<style>
    nav {
        display: none;
    }
</style>

<style scoped>
    #editor {
        height: 85vh;
    }

    .toolbar {
        height: 5vh;
        display: flex;
        width: 100%;
        justify-content: center;
        align-items: center;
        margin-top: 0;
    }

    .toolbar-item {
        margin: 0;
        margin-left: 0.5%;
    }
</style>