"""
A collection of functions to simplfy common VSX operations.
"""
import logging
import os
import re

from otto.lib.otypes import ReturnCode
from otto.appliances.vsx import Vsx
from otto.lib.decorators import wait_until

instance = os.environ.get('instance') or ''
logger = logging.getLogger('otto' + instance + '.lib')
logger.addHandler(logging.NullHandler())


def pv_is_empty(vsx, pv=None):  # TODO: use pv to filter results
    """
    Check if most of the metadata is empty and that extents are
    correctly accounted for. pv parameter is ignored for now
    """
    if not isinstance(vsx, Vsx):
        e = ReturnCode(False)
        e.message = "object is not a Vsx instance"
        return e

    total = 0
    free = 0
    dirty = 0
    meta = 0
    sh = vsx.shelf

    ret = vsx.pvs
    if not ret.status:
        return ret
    p = ret.message
    ret = ReturnCode(True)
    used = calculate_metaext(total, 4096)
    if used != dirty:
        e = "pv has too many dirty extents, should be %d on VSX %s:\n%s" % (used, sh, p)
        logger.error(e)
        ret.status = False
        ret.message = e
    if meta:
        e = "meta extents not zero on VSX %s:\n%s" % (sh, p)
        logger.error(e)
        ret.status = False
        ret.message += "\n%s" % e
    if total != free + dirty:
        e = "pv accounting error on VSX %s:\n%s" % (sh, p)
        logger.error(e)
        ret.status = False
        ret.message += "\n%s" % e
    return ret


def pool_is_empty(vsx, pool):
    """
    Verifypool makes sure that the pool has no extents allocated.
    """
    if not isinstance(vsx, Vsx):
        e = ReturnCode(False)
        e.message = "object is not a Vsx instance"