<template>
    <div style="position: absolute;right: 0;bottom:0;width: 400px;border:1px solid #ccc">

        <v-row>
            <v-col cols="12" md="10">
                <v-file-input ref="file" id="myfile" accept="pdf" label="Please select a file"></v-file-input>

            </v-col>
            <v-col cols="12" md="2">
                <v-btn @click="loadFile" icon><v-icon>mdi-chevron-right</v-icon></v-btn>

            </v-col>
        </v-row>
        <canvas style="zoom:0.3" id="mypdfview"></canvas><br />
        <v-btn v-if="pdf && !loading" :disabled="pageNumber ==1" @click="prevPage" icon><v-icon>mdi-chevron-left</v-icon></v-btn>
        <span v-if="pdf && !loading">{{pageNumber}} / {{pdf.numPages}}</span>
        <v-btn v-if="pdf && !loading" :disabled="pdf.numPages == pageNumber" @click="nextPage" icon><v-icon>mdi-chevron-right</v-icon></v-btn>
        <v-row>
            <v-col cols="12" md="12">
                <v-btn v-if="pdf && !loading" @click="stop">stop pdf share</v-btn>
            </v-col>
        </v-row>
    </div>
</template>

<script>
import pdfjsLib from 'pdfjs-dist/webpack';
const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
});

export default {
    name: "PdfShare",
    props: {
      janusInit: Object,
      onstop: Function,
      username: String,
      myrivid: Number,
      room: Number,
      opaqueId:String
    },
    data: () => ({
        pdf: null,
        pageNumber: 1,
        loading: true,
        pluginHandle: null,
        intervalId: null
        }),
    mounted () {
        pdfjsLib.GlobalWorkerOptions.workerSrc = "/pdf.worker.js"
    },
    methods: {
        renderPage(pageNumber) {
            this.pdf.getPage(pageNumber).then(page => {
                console.log('Page loaded');

                var scale = 1.0;
                var viewport = page.getViewport({scale: scale});

                // Prepare canvas using PDF page dimensions
                var canvas = document.getElementById('mypdfview');
                var context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                // Render PDF page into canvas context
                var renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };

                var renderTask = page.render(renderContext);
                renderTask.promise.then( () => {
                    this.loading = false

                    if (!this.pluginHandle) {
                        // document.getElementById('pdfvid').srcObject = document.getElementById('mypdfview').captureStream(60)

                        this.janusInit.attach(
                            {
                                plugin: "janus.plugin.videoroom",
                                opaqueId: this.opaqueId,
                                success: this.janusPluginSuccess,
                                consentDialog: this.consentDialog,
                                error: this.janusPluginError,
                                mediaState: this.mediaState,
                                webrtcState: this.webrtcState,
                                onmessage: this.janusMessage,
                                onlocalstream: this.onlocalstream
                            }
                        )
                    }
                });
            });
        },
        janusPluginSuccess (pluginHandle) {
            this.pluginHandle = pluginHandle

            var register = { "request": "join", "room": this.room, "ptype": "publisher", "display": this.username + '- PDF' };
            pluginHandle.send({"message": register});

        },
        stop(){
            var unpublish = { "request": "unpublish"};
            this.pluginHandle.send({"message": unpublish});

            this.pluginHandle.detach();

            // reset
            clearInterval(this.intervalId);
            this.pluginHandle = null;
            this.pdf = null;
            this.pageNumber = 1;
            this.loading = true;

            // callback
            this.onstop();
        },
        janusPluginError (error) {
            console.log('error', error)
        },
        consentDialog () {

        },
        mediaState (medium, on) {
            console.log("Janus " + (on ? "started" : "stopped") + " receiving our " + medium);
        },
        webrtcState (on) {
            this.pluginHandle.send({"message": { "request": "configure", "bitrate": 1024*1000 }});
            console.log(on, "webrt")
        },
        janusMessage (msg, jsep) {
            console.log(msg)
            console.log(jsep)
            var event = msg["videoroom"];
            if(event != undefined && event != null) {
                if (event === "joined") {
                    this.createStream()
                }
            }

            if(jsep !== undefined && jsep !== null) {
                this.pluginHandle.handleRemoteJsep({jsep: jsep});
            }
        },
        createStreamSuccess(jsep) {
            console.log('createStreamSuccess')
            var publish = { "request": "configure", "audio": false, "video": true };
            this.pluginHandle.send({"message": publish, "jsep": jsep});

        },
        createStream() {
            console.log('createStream')

            this.pluginHandle.createOffer({
                media: { audioRecv: false, videoRecv: false, audioSend: false, videoSend: true },	// Publishers are sendonly
                stream: document.getElementById('mypdfview').captureStream(),
                success: this.createStreamSuccess,
                error: error => {
                    console.log(error)
                    alert(error)
                }
            })
        },
        pdfTimer () {
            // pdf canvas update hack
            var canvas = document.getElementById('mypdfview');
            var context = canvas.getContext('2d');
            var text = '.';

            context.font = '25px Arial';

            context.fillStyle = '0,0,0';

            var x = 0;

            var y = 0;

            context.fillText(text, x, y);
        },
        nextPage () {
          this.pageNumber++
            this.renderPage(this.pageNumber)

        },
        prevPage () {
          this.pageNumber--
            this.renderPage(this.pageNumber)

        },
        onlocalstream (stream) {
            // Janus.attachMediaStream($('#myvideo').get(0), stream);
            console.log('pdf --------- onlocalstream')

            console.log(stream)
        },

        async loadFile() {

            console.log(this.$refs.file.files)
            var file = document.querySelector('#myfile').files[0]
            var pdfdata = await toBase64(file)
            console.log(pdfdata.split('data:application/pdf;base64,')[1])

            var loadingTask = pdfjsLib.getDocument({data: atob(pdfdata.split('data:application/pdf;base64,')[1])});
            loadingTask.promise.then(pdf => {
                console.log(pdf)
                // var pageNumber = 1;
                this.pdf = pdf
                this.loading = true
                this.intervalId = setInterval(this.pdfTimer, 1000/15)
                this.renderPage(1)


            })
        }
    }
}
</script>

<style scoped>

</style>
