import { event_bus } from './EventBus.service.js'
import { auth_api } from './AuthApi.service.js'

class MessageService {
    constructor() {
        this.listener_interval = 25000
    }

    alert({type, message, timeout = 0, on_dismiss = () => {} }) {
        event_bus.event('message.alert').fire({ type, message, timeout, on_dismiss })
    }

    modal({title, message, buttons = [], inputs = []}) {
        event_bus.event('message.modal').fire({ title, message, buttons, inputs })
    }

    async fetch() {
        const result = await axios.get('/api/v1/message/banners')
        if ( result && result.data && result.data.data ) return result.data.data
    }

    async dismiss(banner_id) {
        return axios.post(`/api/v1/message/banners/read/${banner_id}`)
    }

    async init_listener() {
        if ( await auth_api.get_authenticated_user() ) {
            this.message_ids = []
            this.listener = setInterval(() => this._listener_tick(), this.listener_interval)
            window.addEventListener('beforeunload', () => this.stop_listener())
            try {
                await this._listener_tick()
            } catch (e) {
                this.stop_listener()
            }
        }
    }

    async _listener_tick() {
        const result = await this.fetch()
        if ( result ) {
            for ( const banner of result ) {
                if ( this.message_ids.includes(banner.id) ) continue

                this.message_ids.push(banner.id)
                await this.alert({
                    type: banner.type,
                    message: banner.message,
                    on_dismiss: (e) => {
                        this.dismiss(banner.id).then(() => {
                            this.message_ids = this.message_ids.filter(x => x !== banner.id)
                        })
                    }
                })
            }
        }
    }

    stop_listener() {
        clearInterval(this.listener)
    }
}

const message_service = new MessageService()
export { message_service }
