from django.utils.translation import ugettext as _

from freenasUI.failover.models import Failover
from freenasUI.middleware.notifier import notifier
from freenasUI.system.alert import alertPlugins, Alert, BaseAlert
from freenasUI.truenas import ses


class EnclosureStatusAlert(BaseAlert):

    def run(self):
        encs = ses.Enclosures()
        alerts = []

        for enc in encs:
            healthy = True
            for ele in enc:
                if ele.status == 'Unrecoverable':
                    status = _('UNRECOVERABLE')
                elif ele.status == 'Critical':
                    if ele.name == 'Enclosure' and not Failover.objects.all().exists():
                        continue
                    status = _('CRITICAL')
                elif ele.status == 'Unrecoverable':
                    status = _('UNRECOVERABLE')
                elif ele.status == 'Noncritical':
                    status = _('UNRECOVERABLE')
                else:
                    continue

                healthy = False
                alerts.append(Alert(
                    Alert.CRIT,
                    _('Enclosure %d (%s), %s is %s') % (
                        enc.num,
                        enc.encname,
                        ele.name,
                        status,
                    )
                ))

            if healthy:
                alerts.append(Alert(
                    Alert.OK,
                    _('Enclosure %d (%s) is HEALTHY') % (
                        enc.num,
                        enc.encname,
                    ),
                ))

        return alerts


alertPlugins.register(EnclosureStatusAlert)
