Ext.define("App.view.MessageDetail", {
    extend: "Ext.panel.Panel",
    xtype: "messageDetail",
    id: "messageDetail",

    cls: "shadow",

    style: {
        background: "#ccffc770"
    },

    scrollToBottom: function() {
        var me = this;
        me.down("#msgContainer").setScrollY(99999, true);
    },

    screenPrint: async function(printlist) {
        var me = this;
        bodyHtml = printlist.innerHTML;
        var printPage = window.open("#", "Printing...", "");
        // console.log(headerHtml);
        printPage.document.write(
            '<html><head><link rel="stylesheet" href="/sms/resources/css/main.css"><link rel="stylesheet" href="/sms/resources/css/adminDashboardCSS/try.css"><link rel="stylesheet" href="/sms/resources/css/adminDashboardCSS/Admin-all.css"><link rel="stylesheet" href="/sms/resources/fontawesome-5.10.2/css/all.min.css"><style></style></head><body>'
        );
        printPage.document.write("<h1>Chat Records Of " + me.data.refCode + "</h1>");
        printPage.document.write('<button onclick="myFunction()">Print this page</button>');
        printPage.document.write(bodyHtml);
        printPage.document.write("<script>function myFunction() {window.print();}</script></body></html>");
        printPage.focus();
        // printPage.print();
    },

    Print: function() {
        window.print();
    },

    setData: async function(data) {
        var me = this;
        var title = data.refCode == null ? "Others" : data.refCode;
        me.setTitle(title);
        me.data = data;
        var myMask = new Ext.LoadMask({
            msg: "Please wait...",
            target: me
        });
        await myMask.show();
        const loadData = await Ext.Ajax.request({
            url: App.url("/message/list-msgweb"),
            params: data,
            method: "",
            success: function(response, opts) {
                var result = Ext.decode(response.responseText);
                me.createMsgBox(result.records);
                if (!result.success) {
                    App.showError("Action Failed!");
                    return;
                }
            },
            scope: this
        });
        await myMask.destroy();
        await me.scrollToBottom();
    },

    createMsgBox: function(message) {
        var me = this;
        var msgBox = me.down("#msgContainer");
        msgBox.removeAll(true);
        message.forEach(function(item, index, array) {
            if (item.sendByOther == 1) {
                var inMsg = Ext.create("App.view.InMessage", { msg: item });
                msgBox.add(inMsg);
            } else {
                var outMsg = Ext.create("App.view.OutMessage", { msg: item });
                msgBox.add(outMsg);
            }
        });
    },

    onReplyBtnClick: function() {
        var me = this;
        var msgBox = me.down("#msgContainer");
        var outMsg = Ext.create("App.view.OutMessage");
        var replyText = me.down("#replyText");
        var content = replyText.getValue();
        var url = App.url(me.data.mtId ? "/message/reply-text-message" : "/message/reply-text-message-ref");
        var params = { content: content };

        if (me.data.mtId) {
            Ext.applyIf(params, { mtId: me.data.mtId });
        } else if (me.data.refType && me.data.refId) {
            Ext.applyIf(params, { refType: me.data.refType, refId: me.data.refId, refCode: me.data.refCode });
        } else {
            return;
        }

        outMsg.msg.sendTime = Date.now();
        outMsg.msg.content = content;

        msgBox.add(outMsg);
        Ext.Ajax.request({
            url: url,
            params: params,
            method: "POST",
            success: function(response, opts) {},
            scope: this
        });
        me.scrollToBottom();
        replyText.setValue("");
    },

    onCloseBtnClick: function() {
        var me = this;
        me.setHidden(true);
    },

    initComponent: function() {
        var me = this;

        Ext.apply(me, {
            dockedItems: [
                {
                    xtype: "toolbar",
                    layout: "hbox",
                    style: {
                        "background-color": "#f0f0f0"
                    },
                    padding: 5,
                    dock: "bottom",
                    height: 62,
                    items: [
                        {
                            xtype: "form",
                            itemId: "chatImgUploadForm",
                            width: 40,
                            height: 40,
                            bodyStyle: "background:transparent;",
                            style: "box-shadow:none;",
                            items: [
                                {
                                    xtype: "filefield",
                                    name: "multipartFile",
                                    msgTarget: "side",
                                    width: 40,
                                    height: 40,
                                    anchor: "100%",
                                    buttonOnly: true,
                                    buttonText: "",
                                    buttonConfig: {
                                        iconCls: "x-fa fa-paperclip",
                                        style: {
                                            background: "#05728f",
                                            "border-radius": "50%",
                                            color: "#fff"
                                        },
                                        width: "100%",
                                        height: "100%"
                                    },
                                    listeners: {
                                        change: function(field, value, eOpts) {
                                            if (value) {
                                                field.up("#chatImgUploadForm").submit({
                                                    url: App.url("/message/upload-attachment") + "?_csrf=" + App.csrf,
                                                    params: {
                                                        mtId: me.data.mtId,
                                                        refType: me.data.refType,
                                                        refCode: me.data.refCode,
                                                        refId: me.data.refId
                                                    },
                                                    success: function(form, action) {
                                                        field.reset();
                                                        var responseData = action.result.data;
                                                        Ext.Ajax.request({
                                                            url: App.url("/message/get-file"),
                                                            params: {
                                                                mtId: responseData.messageThreadId,
                                                                mcId: responseData.messageContentId
                                                            },
                                                            method: "GET",
                                                            success: function(response, opts) {
                                                                var result = Ext.decode(response.responseText)
                                                                    .records[0];
                                                                var msgBox = me.down("#msgContainer");
                                                                var outMsg = Ext.create("App.view.OutMessage", {
                                                                    msg: result
                                                                });
                                                                msgBox.add(outMsg);
                                                                me.scrollToBottom();
                                                            },
                                                            failure: function(response, opts) {
                                                                console.log("fail");
                                                            },
                                                            scope: this
                                                        });
                                                    },
                                                    failure: function(form, action) {
                                                        field.reset();
                                                    }
                                                });
                                            }
                                        }
                                    }
                                }
                            ]
                        },
                        {
                            xtype: "textarea",
                            itemId: "replyText",
                            flex: 9,
                            emptyText: "Type a message",
                            ui: "message",
                            style: {
                                "border-radius": "21px !important"
                            },
                            listeners: {
                                change: function(textarea, newValue, oldValue, eOpts) {
                                    if (newValue != "") {
                                        me.down("#replyBtn").setDisabled(false);
                                    } else {
                                        me.down("#replyBtn").setDisabled(true);
                                    }
                                },
                                specialkey: function(field, e) {
                                    if (field.getValue() != "") {
                                        if (e.ctrlKey && e.getKey() == e.ENTER) {
                                            me.onReplyBtnClick();
                                        }
                                    }
                                }
                            }
                        },
                        {
                            xtype: "button",
                            itemId: "replyBtn",
                            width: 40,
                            height: 40,
                            disabled: true,
                            iconCls: "x-fa fa-paper-plane",
                            style: {
                                background: "#05728f",
                                "border-radius": "50%",
                                color: "#fff"
                            },
                            handler: function() {
                                me.onReplyBtnClick();
                            }
                        }
                    ]
                }
            ],
            tools: [
                {
                    type: "print",
                    handler: function() {
                        me.screenPrint(msgContainer);
                    }
                }
            ],
            items: [
                {
                    xtype: "container",
                    id: "msgContainer",
                    itemId: "msgContainer",
                    padding: "10px 5px 5px 0px",
                    style: {
                        background: "#ccffc770"
                    },
                    scrollable: true,
                    items: [],
                    height: "100%",
                    width: "100%"
                }
            ]
        });
        me.callParent(arguments);
    }
});

Ext.define("App.view.OutMessage", {
    extend: "Ext.container.Container",
    xtype: "outMessage",
    msg: {
        senderName: null,
        content: null,
        sendTime: null,
        type: null
    },
    style: {
        "text-align": "right"
    },
    getaudioFile: function(id, skey) {
        return "message-blob/get-audio-message/" + id + "/" + skey;
    },

    initComponent: function() {
        var me = this;
        Ext.apply(me, {
            listeners: {
                added: function() {
                    timestamp = me.msg.sendTime;
                    date = new Date(timestamp);
                    sentTime = Ext.Date.format(date, "Y-m-d H:i");
                    if (me.msg.type == "audio") {
                        var path = me.getaudioFile(me.msg.mbId, me.msg.mbSkey);
                        me.setHtml(
                            "<div class='speech-wrapper'>" +
                                "<div class='chat-outbox-out'>" +
                                "<div class='chatbox'>" +
                                "<div class='txt'>" +
                                "<audio controls name='media'>" +
                                "<source src= " +
                                path +
                                " type='audio/mp4'></audio>" +
                                "</div>" +
                                "<span class='timestamp'>" +
                                sentTime +
                                "</span>" +
                                "</div>" +
                                "</div>" +
                                "</div>"
                        );
                    } else if (me.msg.type == "image") {
                        var path = me.getaudioFile(me.msg.mbId, me.msg.mbSkey);
                        me.setHtml(
                            "<div class='speech-wrapper'>" +
                                "<div class='chat-outbox-out'>" +
                                "<div class='chatbox'>" +
                                "<div class='txt'>" +
                                "<img src=' " +
                                path +
                                "' class='img-width-height' >" +
                                "</div>" +
                                me.msg.filename +
                                "<br>" +
                                "<span class='timestamp'>" +
                                sentTime +
                                "</span>" +
                                "</div>" +
                                "</div>" +
                                "</div>"
                        );
                    } else {
                        me.setHtml(
                            "<div class='speech-wrapper'>" +
                                "<div class='chat-outbox-out'>" +
                                "<div class='chatbox'>" +
                                "<div class='txt'>" +
                                me.msg.content +
                                "</div>" +
                                "<span class='timestamp'>" +
                                sentTime +
                                "</span>" +
                                "</div>" +
                                "</div>" +
                                "</div>"
                        );
                    }
                }
            }
        });
        me.callParent(arguments);
    }
});

Ext.define("App.view.InMessage", {
    extend: "Ext.container.Container",
    xtype: "inMessage",
    style: {
        "text-align": "left"
    },
    msg: {
        senderName: null,
        content: null,
        sendTime: null,
        mbId: null,
        mbSkey: null
    },

    getaudioFile: function(id, skey) {
        return "message-blob/get-audio-message/" + id + "/" + skey;
    },

    initComponent: function() {
        var me = this;
        Ext.apply(me, {
            items: [
                {
                    xtype: "container",
                    id: "try"
                }
            ],
            listeners: {
                added: function() {
                    timestamp = me.msg.sendTime;
                    date = new Date(timestamp);
                    sentTime = Ext.Date.format(date, "Y-m-d H:i");
                    if (me.msg.type == "audio") {
                        var path = me.getaudioFile(me.msg.mbId, me.msg.mbSkey);
                        me.setHtml(
                            "<div class='speech-wrapper'>" +
                                "<div class='chat-outbox-in'>" +
                                "<div class='chatbox_other'>" +
                                "<div class='txt'>" +
                                "<p class='name'>" +
                                me.msg.senderName +
                                "</p>" +
                                "<audio controls name='media'>" +
                                "<source src= " +
                                path +
                                " type='audio/mp4'></audio>" +
                                "</div>" +
                                "<span class='timestamp'>" +
                                sentTime +
                                "</span>" +
                                "</div>" +
                                "</div>" +
                                "</div>"
                        );
                    } else if (me.msg.type == "image") {
                        var path = me.getaudioFile(me.msg.mbId, me.msg.mbSkey);
                        "<div class='speech-wrapper'>" +
                            "<div class='chat-outbox-in'>" +
                            "<div class='chatbox_other'>" +
                            "<div class='txt'>" +
                            "<p class='name'>" +
                            me.msg.senderName +
                            "</p>" +
                            "<img src=' " +
                            path +
                            "' class='img-width-height' >" +
                            "</div>" +
                            me.msg.filename +
                            "<br>" +
                            "<span class='timestamp'>" +
                            sentTime +
                            "</span>" +
                            "</div>" +
                            "</div>" +
                            "</div>";
                    } else {
                        me.setHtml(
                            "<div class='speech-wrapper'>" +
                                "<div class='chat-outbox-in'>" +
                                "<div class='chatbox_other'>" +
                                "<div class='txt'>" +
                                "<p class='name'>" +
                                me.msg.senderName +
                                "</p>" +
                                me.msg.content +
                                "</div>" +
                                "<span class='timestamp'>" +
                                sentTime +
                                "</span>" +
                                "</div>" +
                                "</div>" +
                                "</div>"
                        );
                    }
                }
            }
        });
        me.callParent(arguments);
    }
});
