/* Minification failed. Returning unminified contents.
(2,13-14): run-time error JS1005: Expected '(': ;
(2,13-14): run-time error JS1008: Expected '{': ;
(22,24): run-time error JS1004: Expected ';'
(46,32): run-time error JS1004: Expected ';'
(56,49): run-time error JS1004: Expected ';'
(71,29): run-time error JS1004: Expected ';'
(84,42): run-time error JS1004: Expected ';'
(97,42): run-time error JS1004: Expected ';'
(106,42): run-time error JS1004: Expected ';'
(136,32): run-time error JS1004: Expected ';'
(174,49): run-time error JS1004: Expected ';'
(182,38): run-time error JS1004: Expected ';'
(189,10): run-time error JS1004: Expected ';'
(189,32): run-time error JS1004: Expected ';'
(198,29): run-time error JS1004: Expected ';'
(220,1): run-time error JS1009: Expected '}'
(21,5-39): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: newMessagesWaitingIndicatorHideKey
(15,5-24): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: lastUnseenMessageId
(14,5-24): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: scrollOnMessageLoad
(13,5-21): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: newMessagesCount
(12,5-36): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: loadMessagesWhenPublishInterval
(11,5-22): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: newMessageIdArray
 */
class SocketTm {
    threadId;
    currentPageNumber;
    lastPageNumber;
    newMessagePublishedContainerId;
    newMessageCountContainerId;
    newMessagesWaitingIndicatorContainerId;
    newMessageInsertId;
    newMessageTitleLineId;
    socket;
    newMessageIdArray = [];
    loadMessagesWhenPublishInterval = 0;
    newMessagesCount = 0;
    scrollOnMessageLoad = false;
    lastUnseenMessageId = 0;
    topScrollOffset;
    bottomScrollOffset;
    loadMessageApiUrl;
    onMessageLoadHandler;
    onConnectionChangedHandler;
    newMessagesWaitingIndicatorHideKey = "newMessagesWaitingIndicatorHideKey";
    constructor(config) {
        //config variable
        this.threadId = config.threadId;
        this.currentPageNumber = config.currentPageNumber;
        this.lastPageNumber = config.lastPageNumber;
        this.newMessagePublishedContainerId = config.newMessagePublishedContainerId;
        this.newMessageCountContainerId = config.newMessageCountContainerId;
        this.newMessagesWaitingIndicatorContainerId = config.newMessagesWaitingIndicatorContainerId;
        this.newMessageInsertId = config.newMessageInsertId;
        this.newMessageTitleLineId = config.newMessageTitleLineId;
        this.loadMessageApiUrl = config.loadMessageApiUrl;
        this.onMessageLoadHandler = config.onMessageLoadHandler;
        this.onConnectionChangedHandler = config.onConnectionChangedHandler;
        this.topScrollOffset = config.topScrollOffset;
        this.bottomScrollOffset = config.bottomScrollOffset;
        //local variable
        this.socket = io("https://socket.donanimhaber.com/", { path: '/v4/message-publish/' });
        this.socket.on('connect', () => { this.onConnectionChanged(true); });
        this.socket.on('reconnect', () => { this.onConnectionChanged(true); });
        this.socket.on('disconnect', () => { this.onConnectionChanged(false); });
        this.socket.on("messagePublished", this.onMessagePublished.bind(this));
        window.onscroll = () => this.checkNewMessageContainerPosition(true);
    }

    onConnectionChanged(status) {
        if (status) {
            this.socket.emit("setThreadId", { threadId: this.threadId });
        }

        if (this.onConnectionChangedHandler instanceof Function) {
            this.onConnectionChangedHandler(status);
        }
    }

    checkNewMessageContainerPosition(fromScroll) {
        if (isElementScrolledIntoView(document.getElementById(this.newMessageInsertId))) {
            if (this.currentPageNumber === this.lastPageNumber) {
                this.loadMessagesWhenPublished(fromScroll);
            }
        }

        //otomatik yukleme baslatilmissa
        if (this.loadMessagesWhenPublishInterval !== 0) {
            this.hideNewMessagePublishedNotification();
        }

        this.showNewMessagePublishedNotification();
    }

    onMessagePublished(data) {
        if (data.threadId !== this.threadId) {
            return;
        }

        if (this.lastUnseenMessageId === 0) {
            this.lastUnseenMessageId = data.messageId;
        }
        this.newMessageIdArray.push(data.messageId);
        this.newMessagesCount += 1;
        this.showNewMessagePublishedNotification();
    }

    showNewMessagePublishedNotification() {
        if (this.newMessagesCount <= 0) {
            return;
        }

        var newMessagesAreaScrolledIntoView = isElementScrolledIntoView(document.getElementById(this.newMessageTitleLineId)) || isElementScrolledIntoView(document.getElementById(this.newMessageInsertId));
        //scroll yeni mesaj var barının altinda ise veya otomatik yukleme baslatilmamissa yeni mesaj var bildirimini goster
        if (!newMessagesAreaScrolledIntoView || this.loadMessagesWhenPublishInterval === 0) {
            document.getElementById(this.newMessageCountContainerId).innerText = this.newMessagesCount.toString();
            document.getElementById(this.newMessagePublishedContainerId).style.display = "block";
        }
    }

    hideNewMessagePublishedNotification() {
        //scroll yeni mesaj var barının altinda ise yeni mesaj var bildirimini gizle
        if (isElementScrolledIntoView(document.getElementById(this.newMessageTitleLineId))) {
            this.newMessagesCount = 0;
            this.lastUnseenMessageId = 0;
            document.getElementById(this.newMessagePublishedContainerId).style.display = "none";
        }
    }

    loadMessagesWhenPublished(fromScroll) {
        if (!this.socket.connected) {
            return;
        }

        //yükleme başlatılmışsa 
        if (this.loadMessagesWhenPublishInterval !== 0) {
            //scroll kontrolu degilse yeni mesaj var bildirimi tıklanmistir
            if (!fromScroll) {
                this.scrollToMessageWaitingBar();
            }
            return;
        }

        //son sayfada degilse gormedigi mesaja yonlendir
        if (this.currentPageNumber !== this.lastPageNumber) {
            if (this.newMessageIdArray && this.newMessageIdArray.length > 0) {
                window.location.replace("/mesaj/yonlen/" + this.newMessageIdArray[0]);
            }
            return;
        }

        //scroll kontrolu degilse yeni mesaj var bildirimi tıklanmistir bu yuzden mesaj yuklendiginde yukleniyor barina scroll ediyoruz
        this.scrollOnMessageLoad = !fromScroll;
        //otomatik yuklemeyi baslat
        this.loadMessagesWhenPublishInterval = setInterval(this.loadMessagesInQueue.bind(this), 1000);
        document.getElementById(this.newMessagePublishedContainerId).style.display = "none";
        this.showNewMessagesWaitingIndicatorIfAvailable();
    }

    scrollToMessageWaitingBar() {
        //kullanıcının scroll'u yukarda iken yüklenen mesaj varsa mesaja yoksa yükleniyor barına scroll et
        let unseenMessageElement = document.querySelector('[data-id="' + this.lastUnseenMessageId + '"]');
        if (this.lastUnseenMessageId > 0 && unseenMessageElement) {
            unseenMessageElement.scrollIntoView({
                block: "start",
            });

            let topOffset = 0;
            if (this.topScrollOffset instanceof Function) {
                topOffset = this.topScrollOffset();
            } else if (this.topScrollOffset) {
                topOffset = this.topScrollOffset;
            }
            if (topOffset > 0) {
                window.scrollTo({
                    top: window.scrollY - topOffset
                });
            }
        } else {
            document.getElementById(this.newMessageInsertId).scrollIntoView({
                block: "end"
            });

            let bottomOffset = 0;
            if (this.bottomScrollOffset instanceof Function) {
                bottomOffset = this.bottomScrollOffset();
            } else if (this.bottomScrollOffset) {
                bottomOffset = this.bottomScrollOffset;
            }
            if (bottomOffset > 0) {
                window.scrollTo({
                    top: window.scrollY + bottomOffset
                });
            }
        }
    }

    showNewMessagesWaitingIndicatorIfAvailable() {
        if (localStorage.getItem(this.newMessagesWaitingIndicatorHideKey) === "1") {
            return;
        }

        document.getElementById(this.newMessagesWaitingIndicatorContainerId).style.display = "block";
    }

    hideNewMessagesWaitingIndicator() {
        let containerElement = $('#newMessagesWaitingIndicatorContainer');
        containerElement.css("display", "none");

        localStorage.setItem(this.newMessagesWaitingIndicatorHideKey, '1');
    }

    async loadMessagesInQueue() {
        if (this.newMessageIdArray.length === 0) {
            return;
        }

        let newMessages = this.newMessageIdArray;
        this.newMessageIdArray = [];

        let data = { ThreadId: this.threadId, MessageIdArray: newMessages };
        let response = await $.post(this.loadMessageApiUrl, data).promise();
        if (response.Data) {
            //mesajı html'e insert et
            document.getElementById(this.newMessageInsertId).insertAdjacentHTML('beforebegin', response.Data);
            document.getElementById(this.newMessageTitleLineId).style.display = "block";

            //mesaj yüklendikten sonra yükleniyor görünümüne geç
            this.showNewMessagesWaitingIndicatorIfAvailable();

            //mesaj yüklendiğinde yükleniyor barına scroll edilmesi gerekiyorsa et
            if (this.scrollOnMessageLoad) {
                this.scrollOnMessageLoad = false;
                this.scrollToMessageWaitingBar();
            }

            //mesaj yüklendiğinde çalışacak olan event
            if (this.onMessageLoadHandler instanceof Function) {
                this.onMessageLoadHandler(newMessages);
            }
        }
    }
};
