# -*- python -*-
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007, 2008 by Jan Dittberner.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
#
# Version: $Id$

from sqlalchemy.orm import object_mapper, mapper, relation

from tables import *

class BackendTo(object):
    """Backend transfer object class."""
    def __init__(self, **kwargs):
        for (key, value) in kwargs.items():
            self.__setattr__(key, value)

    def __repr__(self, **kwargs):
        if 'verbose' in kwargs and kwargs['verbose']:
            cols = [col for col in \
                    object_mapper(self).local_table.columns.keys()]
            format = "%(class)s:"
            format = format + ", ".join([col + "=%(" + col + ")s" for col in \
                                         cols])
            data = {'class' : self.__class__.__name__}
        else:
            cols = self._shortkeys
            format = ",".join("%(" + col + ")s" for col in cols)
            data = {}
        data.update(dict([(col, self.__getattribute__(col)) for col in cols]))
        return format % data

class Client(BackendTo):
    """Transfer object class for clients."""
    _shortkeys = ('clientid', 'firstname', 'lastname', 'email')

class Sysuser(BackendTo):
    """Transfer object class for system users."""
    _shortkeys = ("sysuserid", "clientid", "username", "home", "shell")

class Domain(BackendTo):
    """Transfer object class for DNS domains."""
    _shortkeys = ("domainid", "sysuserid", "name", "type")

class Record(BackendTo):
    """Transfer object class for DNS domain records."""
    _shortkeys = ("recordid", "domainid", "name", "type", "content")

client_mapper = mapper(Client, client_table)
sysuser_mapper = mapper(Sysuser, sysuser_table)
domain_mapper = mapper(Domain, domain_table)
record_mapper = mapper(Record, record_table)

client_mapper.add_property("sysusers", relation(Sysuser, backref = 'client'))

sysuser_mapper.add_property("domains", relation(Domain, backref = 'sysuser'))

domain_mapper.add_property("records", relation(Record, cascade = 'all',
                                               backref = 'domain'))