/** This file is part of Reactor.
 *  Copyright (c) 2021-2024 Kedron Holdings LLC, All Rights Reserved.
 *  Reactor is not public domain or open source. Distribution or derivative works are expressly prohibited.
 */

export const version = 24287;

import { mixin } from '/client/util.js';

import Container from '/client/Container.js';
import Data from '/client/Data.js';
import Observer from '/client/Observer.js';

import { _T } from './i18n.js';

// const classes = [ "bi-x-octagon-fill text-danger", "bi-exclamation-triangle text-warning", "bi-info text-info" ];

class AlertWatcher {
    constructor() {
        this.$div = null;
        this.dobj = false;
    }

    async start() {
        this.$div = $( 'a#re-ui-alarms' ).closest( 'div' );
        this.dobj = await Data.getInstance( Container.getInstance( 'states' ), 'sys_alerts' );
        this.subscribe( this.dobj );
        this.show();
    }

    notify( event ) {
        if ( event.type === "data-changed" ) {
            this.show();
        }
    }

    async show() {
        let $link = $( 'a', this.$div );
        if ( 0 === this.dobj.value.alerts.length ) {
            $( 'i.bi:first', $link )
                .removeClass( 'bi-bell-fill text-danger text-warning text-info' )
                .addClass( 'bi-bell text-success' );
            $link.attr( 'title', _T('No alerts.') );
            return;
        }

        let low = null;
        this.dobj.value.alerts.forEach( alert => {
            if ( low === null || alert.severity < low ) {
                low = alert.severity;
            }
        });

        $( 'i.bi', $link )
            .removeClass( 'bi-bell' ).addClass( 'bi-bell-fill' )
            .toggleClass( 'text-danger', low === 0 )
            .toggleClass( 'text-warning', low === 1 )
            .toggleClass( 'text-info', low === 2 )
            .toggleClass( 'text-success', null === low );
        $link.attr( 'title', _T( '{0:d} alerts; see Status.', this.dobj.value.alerts.length ) );
    }
}

mixin( AlertWatcher, Observer );

const _inst = new AlertWatcher();

export default _inst;
