# 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

log = logging.getLogger('freenasUI.truenas.mixins')


class AlertPlugins(object):

    def run(self):
        from freenasUI.middleware.notifier import notifier
        rvs = super(AlertPlugins, self).run()
        current = 'OK'
        for alert in rvs:
            if alert.getDismiss():
                continue
            if alert.getLevel() in (alert.CRIT, alert.WARN):
                current = 'CRIT'
                break
        notifier().set_global_alarm(current)
        return rvs


class Disk:

    def set_enc_slot(self, encnumb, slot):
        """
        Store the enclosure number and slot number within
        the same number/field
        Lets call it an artifice (multiplexer) rather
        than an ugly hack :) lol

        Enclosure number is in an order of magnitude
        of 1000 (arbitrary chosen number)
        """
        self.disk_enclosure_slot = encnumb * 1000 + slot

    def get_enc_slot(self):
        """
        Demux disk_enclosure_slot number
        Read set_enc_slot docstring

        enclosure number = disk_enclosure_slot div 1000
        slot = disk_enclosure_slot mod 1000
        """
        if isinstance(self.disk_enclosure_slot, int):
            return divmod(self.disk_enclosure_slot, 1000)


class Vol:
    def post_delete(self, *args, **kwargs):
        from freenasUI.middleware.notifier import notifier
        try:
            notifier().zpool_enclosure_sync()
        except Exception as e:
            log.error("Failed to sync enclosure: %s", e)
