/** @typedef { import('types/ConversationResponseItem.js').ConversationResponseItem} ConversationResponseItem */

export default function conversations() {
    return {

        /**
         * @type {boolean}
         */
        start: false,

        /**
         * @type {ConversationResponseItem[]}
         */
        data: null,

        /**
         * @type {boolean}
         */
        loading: false,

        /**
         * @type {boolean}
         */
        error: false,

        /**
         * @type {number}
         */
        unviewed: 0,

        /**
         * Request for getting notifications.
         *
         * @return {Promise<void>}
         */
        async getConversations() {
            if( this.loading )
                return;

            this.loading = true;
            this.error = false;

            try {
                const RESPONSE = await fetch('/api/dynamic/conversations', { credentials: "include", headers: { 'X-Requested-With': 'XMLHttpRequest' } });

                if( !RESPONSE.ok )
                    throw new Error(RESPONSE.status)

                let json = await RESPONSE.json()
                if( !json.conversations )
                    throw new Error(RESPONSE.status);

                this.data = json.conversations;


            } catch (error) {
                this.error = true;
            } finally {
                this.loading = false;
            }
        },

        /**
         *
         * @param {HTMLElement} anchorEl
         * @return {Promise<void>}
         */
        async open( anchorEl ){

            if( this.start ){
                this.close();
                return;
            }

            this.start = !this.start;
            if( this.start && !this.data ){
                await this.getConversations();
            }

            if( this.start ){
                Alpine.nextTick(() => window.refreshIcons(document.querySelector('.notifications')))
            }
        },

        /**
         * @return {number}
         */
        get unread(){
            if( !this.data ){
                return this.unviewed;
            }
            return this.data.filter(a => a.is_unread === 0 ).length;
        },

        /**
         *
         */
        close(){
            this.start = false;
        }

    }
}
