"""Exceptions for the web interface."""

import time
from invirt import database
from invirt.database import Machine, MachineAccess

class MyException(Exception):
    """Base class for my exceptions"""
    pass

class InvalidInput(MyException):
    """Exception for user-provided input is invalid but maybe in good faith.

    This would include setting memory to negative (which might be a
    typo) but not setting an invalid boot CD (which requires bypassing
    the select box).
    """
    def __init__(self, err_field, err_value, expl=None):
        MyException.__init__(self, expl)
        self.err_field = err_field
        self.err_value = err_value

class CodeError(MyException):
    """Exception for internal errors or bad faith input."""
    pass

import controls

def cachedproperty(func):
    name = '__cache_' + func.__name__ + '_' + str(id(func))
    def getter(self):
        try:
            return getattr(self, name)
        except AttributeError:
            value = func(self)
            setattr(self, name, value)
            return value
    return property(getter)

class State(object):
    """State for a request"""
    def __init__(self, user, isadmin=False):
        self.username = user
        self.isadmin = isadmin

    def getMachines(self):
        if self.isadmin:
            return Machine.query().join('acl').filter(
                database.or_(MachineAccess.user==self.username,
                             Machine.adminable==True))
        else:
            return Machine.query().join('acl').filter_by(user=self.username)

    machines = cachedproperty(getMachines)
    xmlist_raw = cachedproperty(lambda self: controls.getList())
    xmlist = cachedproperty(lambda self:
                                dict((m, self.xmlist_raw[m.name])
                                     for m in self.machines
                                     if m.name in self.xmlist_raw))

    def clear(self):
        """Clear the state so future accesses reload it."""
        for attr in list(self.__dict__):
            if attr.startswith('__cache_'):
                delattr(self, attr)
