# -*- coding: UTF-8 -*-
#
# Copyright (C) 2007 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$

import sqlalchemy, logging
from gnuviechadmin.exceptions import *
from BackendEntity import *

class BackendEntityHandler(object):
    def __init__(self, entityclass, toclass, verbose = False):
        self.logger = logging.getLogger("%s.%s" % (
            self.__class__.__module__, self.__class__.__name__))
        self.entityclass = entityclass
        self.toclass = toclass
        self.verbose = verbose

    def create(self, **kwargs):
        """Create a new entity of the managed type with the fields set
        to the values in kwargs."""
        self.logger.debug("create with params %s", str(kwargs))
        sess = sqlalchemy.create_session()
        transaction = sess.create_transaction()
        delegate = self.toclass(**kwargs)
        entity = self.entityclass(delegate, self.verbose)            
        try:
            sess.save(delegate)
            sess.flush()
            sess.refresh(delegate)
            entity.create_hook(sess)
            sess.flush()
            transaction.commit()
        except:
            transaction.rollback()
            self.logger.exception("Exception in create.")
            raise

    def fetchall(self, **kwargs):
        """Fetches all entities of the managed entity type."""
        self.logger.debug("fetchall with params %s", str(kwargs))
        session = sqlalchemy.create_session()
        query = session.query(self.toclass)
        if kwargs:
            allentities = query.select_by(**kwargs)
        else:
            allentities = query.select()
        return [self.entityclass(entity, self.verbose) \
                for entity in allentities]

    def delete(self, pkvalue):
        """Deletes the entity of the managed entity type that has the
        specified primary key value."""
        self.logger.debug("delete with primary key %s", str(pkvalue))
        sess = sqlalchemy.create_session()
        transaction = sess.create_transaction()
        try:
            to = sess.query(self.toclass).get(pkvalue)
            if to:
                entity = self.entityclass(to, self.verbose)
                self.logger.info("delete %s", str(entity))
                if self.verbose:
                    print "delete %s" % (str(entity))
                entity.delete_hook(sess)
                sess.delete(to)
            sess.flush()
            transaction.commit()
        except Exception, e:
            transaction.rollback()
            self.logger.exception("Exception in delete.")
            raise