# Copyright (c) 2018 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.

from django.utils.translation import ugettext as _

from freenasUI.middleware.client import client, ClientException
from freenasUI.middleware.notifier import notifier
from freenasUI.system.alert import alertPlugins, Alert, BaseAlert


class FailoverBootVolumeStatusAlert(BaseAlert):

    def on_volume_status_not_healthy(self, state, status):
        return Alert(
            Alert.CRIT,
            _('The boot volume state is %(state)s: %(status)s') % {
                'state': state,
                'status': status,
            },
        )

    def run(self):
        alerts = []

        if not notifier().failover_licensed():
            return alerts

        try:
            with client as c:
                state, status = c.call('failover.call_remote', 'notifier.zpool_status', ['freenas-boot'])
        except Exception as e:
            alerts.append(Alert(Alert.CRIT, _(
                'Failed to check failover boot volume status with the other node: %s' % (e,)
            )))
        else:
            if state == 'HEALTHY':
                pass
            else:
                alerts.append(
                    self.on_volume_status_not_healthy(state, status)
                )

        return alerts


alertPlugins.register(FailoverBootVolumeStatusAlert)
