var VPDiskusi = (function () {
    let vp_template = `
    <div v-if="errMsg" class="toast toast-autohide custom-toast-1 toast-danger home-page-toast fade show" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="7000" data-bs-autohide="true">
        <div class="toast-body">
          <svg class="bi bi-bookmark-check text-white" width="30" height="30" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
            <path fill-rule="evenodd" d="M2 2a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v13.5a.5.5 0 0 1-.777.416L8 13.101l-5.223 2.815A.5.5 0 0 1 2 15.5V2zm2-1a1 1 0 0 0-1 1v12.566l4.723-2.482a.5.5 0 0 1 .554 0L13 14.566V2a1 1 0 0 0-1-1H4z"></path>
            <path fill-rule="evenodd" d="M10.854 5.146a.5.5 0 0 1 0 .708l-3 3a.5.5 0 0 1-.708 0l-1.5-1.5a.5.5 0 1 1 .708-.708L7.5 7.793l2.646-2.647a.5.5 0 0 1 .708 0z"></path>
          </svg>
          <div class="toast-text ms-3 me-2">
            <p class="mb-1 text-white">Error!</p><small class="d-block">{{errMsg}}</small>
          </div>
        </div>
        <button class="btn btn-close btn-close-white position-absolute p-1" type="button" data-bs-dismiss="toast" aria-label="Close"></button>
        <span class="toast-autohide-animation" style="animation-duration: 7000ms;"></span>
      </div>

    <div class="message-box mb-2" >
        <div class="container">
            <div class="chat-content-wrap" @scroll="msgScrl" ref="messagesBox">
                <template v-for="(conversation,index) in conversations">

                    <template v-if="index!=0">
                        <div v-if="conversation.sdtm.format('YYYY-MM-DD')==mm().subtract(1,'d').format('YYYY-MM-DD')&&conversation.sdtm.format('YYYY-MM-DD')!=conversations[index-1].sdtm.format('YYYY-MM-DD')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span style="background-color: rgb(226, 233, 254);padding: 0px 10px;">Kemarin</span>
                        </div>
                        <div v-else-if="conversation.sdtm.format('YYYY-MM-DD')==mm().format('YYYY-MM-DD')&&conversation.sdtm.format('YYYY-MM-DD')!=conversations[index-1].sdtm.format('YYYY-MM-DD')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span style="background-color: rgb(226, 233, 254);padding: 0px 10px;">Hari Ini</span>
                        </div>
                        <div v-else-if="conversation.sdtm.format('YYYY-MM')!=conversations[index-1].sdtm.format('YYYY-MM')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span v-if="conversation.sdtm.format('YYYY')==mm().format('YYYY')" style="background-color: rgb(226, 233, 254);padding: 0px 10px;">{{conversation.sdtm.format('DD MMMM')}}</span>
                            <span v-else style="background-color: rgb(226, 233, 254);padding: 0px 10px;">{{conversation.sdtm.format('DD MMMM YYYY')}}</span>
                        </div>
                    </template>
                    <template v-else>
                        <div v-if="conversation.sdtm.format('YYYY-MM-DD')==mm().subtract(1,'d').format('YYYY-MM-DD')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span style="background-color: rgb(226, 233, 254);padding: 0px 10px;">Kemarin</span>
                        </div>
                        <div v-else-if="conversation.sdtm.format('YYYY-MM')!=mm().format('YYYY-MM')" class="my-4" style="width: 100%;height: 12px;border-bottom: 1px solid black;text-align: center">
                            <span v-if="conversation.sdtm.format('YYYY')==mm().format('YYYY')" style="background-color: rgb(226, 233, 254);padding: 0px 10px;">{{conversation.sdtm.format('DD MMMM')}}</span>
                            <span v-else style="background-color: rgb(226, 233, 254);padding: 0px 10px;">{{conversation.sdtm.format('DD MMMM YYYY')}}</span>
                        </div>
                    </template>

                <div class="mt-2" v-if="conversation.is_me==0" :ref="conversation.id">
                    <small>
                        <strong>{{conversation.nama}}</strong>
                    </small>
                    <div class="single-chat-item">
                        <!-- User Avatar -->
                        <div v-if="false" class="user-avatar mt-1">
                            <!-- If the user avatar isn't available, will visible the first letter of the username.-->
                            <span class="name-first-letter">A</span>
                        </div>
                        <!-- User Message -->
                        <div class="user-message">
                            <div class="message-content">
                                <div class="single-message" :class="conversation.is_teacher==1?'is-teacher':''" >
                                <p v-html="conversation.conversation"></p>
                                </div>
                            </div><!-- Time and Status -->
                            <div class="message-time-status">
                                <div class="sent-time">{{conversation.sdtm.format('HH:mm')}}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div v-else-if="!conversation.deleting" :ref="conversation.id" class="single-chat-item outgoing">
                    <!-- User Avatar -->
                    <div v-if="false" class="user-avatar mt-1">
                        <!-- If the user avatar isn't available, will visible the first letter of the username. -->
                        <span class="name-first-letter">A</span>
                    </div><!-- User Message -->
                    <div class="user-message" :style="!conversation.sending?'cursor:pointer':''" @mousedown="!conversation.sending?chatpress(conversation.id):''" @mouseleave="!conversation.sending?schatpress():''" @mouseup="!conversation.sending?schatpress():''" @touchstart="!conversation.sending?chatpress(conversation.id):''" @touchend="!conversation.sending?schatpress():''" @touchcancel="!conversation.sending?schatpress():''">
                        <div class="message-content">
                            <div :class="conversation.sending?'warning':(conversation.failed?'danger':'')" class="single-message is-me" >
                                <p  v-html="conversation.conversation"></p>
                            </div>
                            <div v-if="false" class="dropstart">
                                <button class="btn btn-options dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"><i class="bi bi-three-dots-vertical"></i></button>
                                    <ul class="dropdown-menu">
                                        <li><a @click="deleteConversation(conversation.id)" href="javascript:void(0)"><i class="bi bi-trash"></i>Hapus</a></li>
                                    </ul>
                            </div>
                        </div><!-- Time and Status -->
                        <div class="message-time-status">
                            <div class="sent-time">{{conversation.sdtm.format('HH:mm')}}</div>
                                <div v-if="conversation.sending" class="sent-status text-warning">
                                    <i aria-hidden="true" class="fas fa-paper-plane"></i>
                                </div>
                                <div v-else-if="conversation.failed" class="sent-status text-danger">
                                    <i aria-hidden="true" class="fas fa-times"></i>
                                </div>
                                <div v-else class="sent-status seen">
                                    <i aria-hidden="true" class="bi bi-check-lg"></i>
                                </div>
                        </div>
                    </div>
                </div>

                </template>
            </div>
        </div>
    </div>
    <div class="chat-footer">
        <div class="container h-100">
            <div class="chat-footer-content h-100 d-flex align-items-center">
                    <!-- Message -->
                    <div class="px-3 w-100">
                        <editor class="w-100 h-100 form-control" v-model="message" :tinymceScriptSrc="$store.state.config.base_url+'/vendors/tinymce/js/tinymce/tinymce.min.js'" :init="tinymce"></editor>
                    </div>
                    <div v-if="false" class="dropup mx-2">
                        <button class="btn btn-add-file dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <svg class="bi bi-plus-circle" xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" viewBox="0 0 16 16">
                            <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"></path>
                            <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"></path>
                            </svg>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a href="javascript:void(0)"><i class="bi bi-card-image"></i>Gambar</a></li>
                        </ul>
                        </div>
                    <!-- Send -->
                    <button @click="sendMsg()" class="btn btn-submit mx-2" type="button">
                        <svg class="bi bi-cursor" xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" viewBox="0 0 16 16">
                            <path d="M14.082 2.182a.5.5 0 0 1 .103.557L8.528 15.467a.5.5 0 0 1-.917-.007L5.57 10.694.803 8.652a.5.5 0 0 1-.006-.916l12.728-5.657a.5.5 0 0 1 .556.103zM2.25 8.184l3.897 1.67a.5.5 0 0 1 .262.263l1.67 3.897L12.743 3.52 2.25 8.184z"></path>
                        </svg>
                    </button>
            </div>
        </div>
    </div>



    <div class="modal fade" id="modal-chatpress" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-md modal-dialog-centered">
            <div class="modal-content card-style">
                <div class="modal-body px-0">
                    <div class="content">

                        <ul v-if="chatholddata" class="list-group list-group-flush">
                            <li v-if="!chatholddata.loading" data-bs-dismiss="modal" @click="chatholddata.failed?conversations.splice(conversations.findIndex(v=>v==chathold.id),1):deleteConversation(chatholddata.id)" style="cursor:pointer"  class="list-group-item">Hapus</li>
                            <li v-if="chatholddata.failed" data-bs-dismiss="modal" @click="resend(chatholddata.id)" style="cursor:pointer" class="list-group-item">Kirim Ulang</li>
                            <li v-if="chatholddata.failed" data-bs-dismiss="modal" @click="message=chatholddata.conversation,deleteConversation(chatholddata.id)" style="cursor:pointer" class="list-group-item">Ubah</li>
                        </ul>

                    </div>
                </div>
            </div>
        </div>
    </div>
    `;
    return {
        name: "diskusi",
        template: vp_template,
        data() {
            return {
                conversations: [],
                errMsg: '',
                message: '',
                csrf: {
                    name: null,
                    value: null,
                },
                chathold: {
                    timeout: null,
                    modal: null,
                    id: null,
                },
                lastOld: (new Date()).getTime(),
                tinymce: {
                    menubar: false,
                    images_upload_handler: this.images_upload_handler,
                    plugins: ['image', 'paste', 'autoresize'],
                    toolbar_location: 'bottom',
                    menubar: false,
                    toolbar: false,
                    inline: true,
                    setup: (editor) => {
                        editor.on('keydown', this.shortcut);
                    },
                    content_style: "p { margin: 0; }",
                },

            }
        },
        mounted() {

            this.notification = new Audio('/assets/audio/elearning/notification.mp3');
            this.initConversation();
            this.setLoop();
            this.body = document.body;
            this.doc = document.documentElement;
        },
        methods: {
            chatpress(id) {
                if (this.chathold.timeout) clearTimeout(this.chathold.timeout);
                this.chathold.timeout = setTimeout(() => {
                    this.mdlchatpress();
                    this.chathold.id = id;
                }, 400);
            },
            schatpress() {
                if (this.chathold.timeout) clearTimeout(this.chathold.timeout);
            },
            shortcut(e) {
                if (!e.shiftKey && e.key == "Enter") {
                    // e.preventDefault();
                }
            },
            setLoop() {
                this.rand = this.conversations.length < 5 ? 2000 : Math.floor(Math.random() * 15000) + 2000;
                setTimeout(() => {
                    this.autoLoadNewest();
                    this.setLoop();
                }, this.rand);
            },
            autoLoadNewest() {
                let dt = new Date();
                dt.setSeconds(dt.getSeconds() - 2);
                if (this.lastFetch > dt.getTime()) return;
                if (this.conversations.length <= 0) return this.initConversation();
                this.loadNewConversations();
            },
            msgScrl(e) {
                this.doc = (this.doc.clientHeight) ? this.doc : this.body;
                if (this.doc.scrollTop <= 0 && this.lastOld < (new Date()).getTime()) {
                    if (this.conversations.length <= 0) return this.initConversation();
                    return this.loadOldConversations();
                }
                if (this.doc.scrollHeight - this.doc.scrollTop === this.doc.clientHeight) {
                    if (this.conversations.length <= 0) return this.initConversation();
                    return this.loadNewConversations();
                }
            },
            initConversation() {
                if (this.loading) return;
                this.loading = true;
                this.lastFetch = (new Date()).getTime();
                axios({
                    method: 'get',
                    url: window.location.href + "/init",
                }).then((response) => {

                    if (!isObject(response.data)) return setTimeout(this.initConversation, 5000);
                    this.conversations = response.data.conversations.map(v => {
                        v.sdtm = mm({ unix: v.created_at });
                        return v;
                    });
                    if (this.conversations.length > 0) document.getElementById('active-status').innerText = "Percakapan Terakhir " + this.timeLastChat();
                    document.getElementById('mapel_name').innerText = response.data.nama_mapel;
                    setTimeout(() => {
                        this.toLastMsg()
                        this.toLastMsg()
                        setTimeout(() => {
                            window.onscroll = this.msgScrl;
                        }, 200)
                    }, 100)
                }, (error) => {
                    setTimeout(this.initConversation, 1000);
                }).finally(() => this.loading = false);
            },
            loadOldConversations() {
                if (this.loading) return;
                this.loading = true;
                let lid = this.conversations[0].id;
                this.lastFetch = (new Date()).getTime();
                axios({
                    method: 'get',
                    url: window.location.href + "/oldest?lid=" + lid,
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadOldConversations, 5000);
                    response.data.conversations = response.data.conversations
                        .filter(v => this.conversations.findIndex(sv => sv.id == v.id) == -1)
                        .map(v => {
                            v.sdtm = mm({ unix: v.created_at });
                            return v;
                        }).reverse();
                    this.conversations = [...response.data.conversations, ...this.conversations];
                    let lid2 = this.conversations[response.data.conversations.length];
                    let dt = new Date();
                    if (response.data.conversations.length > 0 && lid2) {
                        dt.setSeconds(dt.getSeconds() + 1);
                        this.lastOld = dt.getTime();
                        setTimeout(() => {
                            if (this.$refs[lid2.id]) this.$refs[lid2.id].scrollIntoView({ block: "nearest", inline: "nearest" })
                        }, 50);
                    }
                    if (response.data.conversations.length <= 0) {
                        dt.setMinutes(dt.getMinutes() + 3);
                        this.lastOld = dt.getTime();
                    }
                }, (error) => {
                    setTimeout(this.loadOldConversations, 5000);
                }).finally(() => this.loading = false);
            },
            loadNewConversations() {
                if (this.loading) return;
                this.loading = true;
                let lid = this.conversations[this.conversations.length - 1].id;
                this.lastFetch = (new Date()).getTime();
                axios({
                    method: 'get',
                    url: window.location.href + "/newest?lid=" + lid,
                }).then((response) => {
                    if (!isObject(response.data)) return setTimeout(this.loadNewConversations, 5000);
                    response.data.conversations = response.data.conversations
                        .filter(v => this.conversations.findIndex(sv => sv.id == v.id) == -1)
                        .map(v => {
                            v.sdtm = mm({ unix: v.created_at });
                            return v;
                        })
                    if (response.data.conversations.length > 0 && this.doc.scrollHeight - this.doc.scrollTop === this.doc.clientHeight) {
                        setTimeout(() => {
                            this.toLastMsg()
                        }, 100);
                    }
                    this.conversations = [...this.conversations, ...response.data.conversations];
                    if (response.data.conversations.length > 0) {
                        this.notification.play();
                    }
                    if (this.conversations) document.getElementById('active-status').innerText = "Percakapan Terakhir " + this.timeLastChat();
                }, (error) => {
                    setTimeout(this.loadNewConversations, 1000);
                }).finally(() => this.loading = false);
            },
            toLastMsg() {
                if (this.conversations.length > 0) window.scrollTo(0, document.body.scrollHeight);
            },
            resend(id) {
                let msg = this.conversations.find(v => v.id == id);
                if (!msg) return;
                if (msg.sending) return;
                if (!msg.failed) return;
                msg.sending = true;
                msg.failed = false;
                axios({
                    method: 'put',
                    data: { msg: { id: msg.id, conversation: msg.conversation }, [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value },
                    url: window.location.href + "/add",
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    msg.id = response.data.id;
                    msg.sending = false;
                    msg.failed = false;
                }, (error) => {
                    msg.sending = false;
                    msg.failed = true;
                });
            },
            sendMsg() {
                if (this.message.length <= 0) return;
                let msg = {
                    id: makeid(),
                    nama: this.$store.state.config.person.name,
                    is_me: "1",
                    sending: true,
                    failed: false,
                    conversation: this.message,
                    nomor_induk: this.$store.state.config.person.nomor_induk,
                    sdtm: this.mm(),
                    created_at: this.mm().unix(),
                    updated_at: this.mm().unix(),
                }
                this.conversations.push(msg);
                this.message = '';
                setTimeout(() => {
                    this.toLastMsg();
                }, 50)
                axios({
                    method: 'put',
                    data: { msg: { id: msg.id, conversation: msg.conversation }, [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value },
                    url: window.location.href + "/add",
                }).then((response) => {
                    if (!isObject(response.data)) return this.errMsg = gaem({
                        response
                    }, response.data);
                    let m = this.conversations.find(v => v.id == msg.id);
                    m.id = response.data.id;
                    m.sending = false;
                    m.failed = false;
                    if (this.conversations.length <= 0) return this.initConversation();
                    return this.loadNewConversations();
                }, (error) => {
                    let m = this.conversations.find(v => v.id == msg.id);
                    m.sending = false;
                    m.failed = true;
                });
            },
            deleteConversation(id) {
                let chat = this.conversations.find(v => v.id == id);
                if (!chat) return;
                if (chat.failed) return this.conversations.splice(this.conversations.findIndex(v => v == chat.id), 1);
                if (chat.deleting) return;
                SwalDelete({
                    params: {
                        title: 'Hapus Percakapan',
                        text: 'Ini akan menghapus percakapan, apakah anda yakin?',
                        type: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Ya, Hapus!'
                    },
                    confirmed: () => {
                        chat.deleting = true;
                        axios({
                            method: 'delete',
                            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, },
                            url: window.location.href + "/delete/" + btoa(id),
                        }).then((response) => {
                            let si = this.conversations.findIndex(v => v.id == id);
                            if (si == -1) return;
                            this.conversations.splice(si, 1);
                        }, (error) => {
                            chat.deleting = false;
                            this.errMsg = gaem(error, "Gagal Hapus Pesan, Silahkan Coba Lagi");
                        });
                    }
                });
            },
            images_upload_handler(blobInfo, success, failure, progress) {
                var xhr, formData;

                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', window.location.href + '/imageUploader');

                xhr.upload.onprogress = function (e) {
                    progress(e.loaded / e.total * 100);
                };

                xhr.onload = function () {
                    var json;

                    if (xhr.status === 403) {
                        failure('HTTP Error: ' + xhr.status, { remove: true });
                        return;
                    }

                    if (xhr.status < 200 || xhr.status >= 300) {
                        failure('HTTP Error: ' + xhr.status);
                        return;
                    }

                    json = JSON.parse(xhr.responseText);

                    if (!json || typeof json.location != 'string') {
                        failure('Invalid JSON: ' + xhr.responseText);
                        return;
                    }

                    success(json.location);
                };

                xhr.onerror = function () {
                    failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
                };

                formData = new FormData();
                formData.append('file', blobInfo.blob(), blobInfo.filename());
                formData.append([this.$store.state.config.csrf.name], this.$store.state.config.csrf.value);

                xhr.send(formData);
            },
            mm() {
                return mm();
            },
            timeLastChat() {
                if (!this.conversations.length) return '';
                if (this.conversations[this.conversations.length - 1].sdtm.format('YYYY-MM-DD') == this.mm().format('YYYY-MM-DD')) return this.conversations[this.conversations.length - 1].sdtm.format('HH:mm')
                if (this.conversations[this.conversations.length - 1].sdtm.format('YYYY-MM-DD') == this.mm().subtract(1, 'd').format('YYYY-MM-DD')) return `Kemarin ${this.conversations[this.conversations.length - 1].sdtm.format('HH:mm')}`;
                if (this.conversations[this.conversations.length - 1].sdtm.format('YYYY-MM-DD') == this.mm().subtract(1, 'w').format('YYYY-MM-DD')) return `Minggu Lalu ${this.conversations[this.conversations.length - 1].sdtm.format('HH:mm')}`;
                if (this.conversations[this.conversations.length - 1].sdtm.format('YYYY-MM') == this.mm().format('YYYY-MM')) return this.conversations[this.conversations.length - 1].sdtm.format('DD HH:mm');
                if (this.conversations[this.conversations.length - 1].sdtm.format('YYYY') == this.mm().format('YYYY')) return this.conversations[this.conversations.length - 1].sdtm.format('DD MMMM HH:mm');
                return conversations[conversations.length - 1].sdtm.format('YYYY-MM-DD HH:mm');
            },
            mdlchatpress(e = 'show') {
                if (!this.chatpress.modal) {
                    this.chatpress.modal = new bootstrap.Modal(document.getElementById('modal-chatpress'));
                }
                switch (e) {
                    case "hide":
                        this.chatpress.modal.hide();
                        break;
                    case "show":
                        this.chatpress.modal.show();
                        break;
                    case "toggle":
                        this.chatpress.modal.toggle();
                        break;
                    case "dispose":
                        this.chatpress.modal.dispose();
                        break;
                }
            },
        },
        computed: {
            chatholddata() {
                return this.conversations.find(v => v.id == this.chathold.id)
            }
        }
    }
})();
