from invirt.config import structs as config
import sqlalchemy

from sqlalchemy import *
from sqlalchemy import orm
from sqlalchemy.orm import create_session, relation

from sqlalchemy.ext.sessioncontext import SessionContext
from sqlalchemy.ext.assignmapper import assign_mapper

def connect(uri = config.db.uri):
    """ Connect to a given database URI"""
    global session
    
    engine = sqlalchemy.create_engine(uri, pool_timeout=5)
    meta.bind = engine
    
    session = Session(bind=engine)

def clear_cache():
    """Clear sqlalchemy's cache
    """

    session.clear()

meta = MetaData()
Session = orm.sessionmaker(transactional=False, autoflush=False)

machine_table = Table('machines', meta,
       Column('machine_id', Integer, primary_key=True, nullable=False),
       Column('name', String, nullable=False),
       Column('description', String, nullable=False),
       Column('memory', Integer, nullable=False),
       Column('owner', String, nullable=False),
       Column('contact', String, nullable=False),
       Column('uuid', String, nullable=False),
       Column('administrator', String, nullable=False, default=False),
       Column('type_id', String, ForeignKey('types.type_id'), nullable=False),
       Column('autorestart', Boolean, nullable=False, default=False),
       Column('cpus', Integer, nullable=False, default=1),
       Column('adminable', Boolean, nullable=False, default=False))

nic_table = Table('nics', meta,
       Column('machine_id', Integer, ForeignKey('machines.machine_id'), nullable=True),
       Column('mac_addr', String, nullable=False, primary_key=True),
       Column('ip', String, nullable=False, unique=True),
       Column('hostname', String, nullable=True))

disk_table = Table('disks', meta,
       Column('machine_id', Integer, ForeignKey('machines.machine_id'), nullable=False),
       Column('guest_device_name', String, nullable=False),
       Column('size', Integer, nullable=False),
       PrimaryKeyConstraint('machine_id', 'guest_device_name'))

types_table = Table('types', meta,
       Column('type_id', String, primary_key=True, nullable=False),
       Column('description', String, nullable=False),
       Column('hvm', Boolean, nullable=False),
       Column('apic', Boolean, nullable=False),
       Column('acpi', Boolean, nullable=False),
       Column('pae', Boolean, nullable=False))

mirrors_table = Table('mirrors', meta,
       Column('mirror_id', String, primary_key=True, nullable=False),
       Column('uri_prefix', String, nullable=False))

cdroms_table = Table('cdroms', meta,
       Column('cdrom_id', String, primary_key=True, nullable=False),
       Column('description', String, nullable=False),
       Column('mirror_id', String, ForeignKey('mirrors.mirror_id')),
       Column('uri_suffix', String))

autoinstalls_table = Table('autoinstalls', meta,
       Column('autoinstall_id', String, primary_key=True, nullable=False),
       Column('description', String, nullable=False),
       Column('type_id', String, ForeignKey('types.type_id'), nullable=False),
       Column('distribution', String, nullable=False),
       Column('mirror', String, nullable=False))

machine_access_table = Table('machine_access', meta,
       Column('machine_id', Integer, ForeignKey('machines.machine_id', ondelete='CASCADE'), nullable=False, index=True),
       Column('user', String, nullable=False, index=True),
       PrimaryKeyConstraint('machine_id', 'user'))

class Machine(object):
    def __repr__(self):
        return "<Machine %s: name='%s' owner='%s'>" % (self.machine_id, self.name, self.owner)

class MachineAccess(object):
    def __repr__(self):
        return "<MachineAccess machine='%s' user='%s'>" % (self.machine, self.user)

class NIC(object):
    def __repr__(self):
        return "<NIC: mac='%s' machine='%s' ip='%s' hostname='%s'>" % (self.mac_addr, self.machine_id, self.ip, self.hostname)

class Disk(object):
    def __repr__(self):
        return "<Disk: machine=%s device=%s size=%s>" % (self.machine_id, self.guest_device_name, self.size)

class Type(object):
    def __repr__(self):
        return "<Type %s: %s>" % (self.type_id, self.description)

class Mirror(object):
    def __repr__(self):
        return "<Mirror %s>" % (self.mirror_id)

class CDROM(object):
    def __repr__(self):
        return "<CDROM %s: %s>" % (self.cdrom_id, self.description)

class Autoinstall(object):
    def __repr__(self):
        return "<Autoinstall %s: %s (%s)>" % (self.autoinstall_id, self.description, self.type.type_id)

orm.mapper(Machine, machine_table,
              properties={'nics': relation(NIC, backref="machine", lazy=False),
                          'disks': relation(Disk, backref="machine", lazy=False),
                          'type': relation(Type, lazy=False),
                          'acl': relation(MachineAccess, backref="machine", lazy=False, passive_deletes=True, cascade="all, delete-orphan")});
orm.mapper(MachineAccess, machine_access_table)
orm.mapper(NIC, nic_table)
orm.mapper(Disk, disk_table)
orm.mapper(Type, types_table)
orm.mapper(Mirror, mirrors_table)
orm.mapper(CDROM, cdroms_table,
               properties={'mirror': relation(Mirror, backref="cdroms")})
orm.mapper(Autoinstall, autoinstalls_table)
