# Copyright (c) 2015 iXsystems, Inc.
# All rights reserved.
# This file is a part of TrueNAS
# and may not be copied and/or distributed
# without the express permission of iXsystems.

import logging

from django.utils.translation import ugettext as _

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

log = logging.getLogger('system.alertmods.enclosure_status')


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

                # Enclosure element is CRITICAL in single head, ignore this for now
                # See #11918
                if ele.name == 'Enclosure':
                    continue

                # The 1.8V sensor is bugged on the echostream enclosure.  The
                # management chip loses it's mind and claims undervoltage, but
                # scoping this confirms the voltage is fine.
                # Ignore alerts from this element.
                # #10077
                if enc.name == 'ECStream 3U16+4R-4X6G.3 d10c':
                    if ele.descriptor == '1.8V Sensor':
                        continue

                healthy = False
                alerts.append(Alert(
                    Alert.CRIT,
                    _('Enclosure %d (%s), %s is %s') % (
                        enc.num,
                        enc.encname,
                        ele.name,
                        status,
                    )
                ))
                # Log the element, see #10187
                log.warn(
                    'Element %s: %s, status: %s (%s), descriptor: %s',
                    hex(ele.slot),
                    ele.name,
                    ele.status,
                    hex(ele.value_raw),
                    ele.descriptor,
                )

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

        return alerts


alertPlugins.register(EnclosureStatusAlert)
