
'''
 * This file was generated by ProCG version 2.0
 *
 * File name:	fms\data\sql_alchemy\data_manager_base.py
 * Language:	Python
 * Database:	My Sql
 *
 * Copyright (c) 2002-2016 iGenXSoft.
 * For more information visit http://www.igenxsoft.com
'''

import logging

# from orm.services.flavor_manager.fms_rest.logic.error_base import DuplicateEntityError
from orm.services.flavor_manager.fms_rest.data.sql_alchemy.flavor.flavor_record import FlavorRecord
from oslo_db.sqlalchemy import session as db_session

from pecan import conf
from sqlalchemy.event import listen

LOG = logging.getLogger(__name__)


# event handling
def on_before_flush(session, flush_context, instances):
    for model in session.new:
        if hasattr(model, "validate"):
            model.validate("new")

    for model in session.dirty:
        if hasattr(model, "validate"):
            model.validate("dirty")


class DataManager(object):

    def __init__(self, connection_string=None):
        if not connection_string:
            connection_string = conf.database.connection_string

        try:
            self._engine_facade = db_session.EngineFacade(connection_string, autocommit=False)
        except Exception:
            nagios_message = "CRITICAL|CONDB001 - "
            err_message = "Could not establish database connection"
            LOG.error(nagios_message + err_message)
            raise Exception(err_message)

        # self._engine = create_engine(connection_string, echo=True)
        # self.session_maker = sessionmaker(bind=self.get_engine())
        self._session = None
        listen(self.session, 'before_flush', on_before_flush)
        self.flavor_record = None

    def get_engine(self):
        return self._engine_facade.get_engine()

    @property
    def engine(self):
        return self.get_engine()

    def get_session(self):
        if not self._session:
            self._session = self._engine_facade.get_session()
        return self._session

    @property
    def session(self):
        return self.get_session()

    def begin_transaction(self):
        # self.session.begin()
        # no need to begin transaction - the transaction is open automatically
        pass

    def flush(self):
        try:
            self.session.flush()
        except Exception as exp:
            raise

    def commit(self):
        self.session.commit()

    def rollback(self):
        self.session.rollback()

    def close(self):
        self.session.close()
        self.engine.dispose()

    def get_record(self, record_name):
        if record_name == "Flavor" or record_name == "flavor":
            # if not hasattr(self, "flavor_record"):
            #    self.flavor_record = FlavorRecord(self.session)
            if not self.flavor_record:
                self.flavor_record = FlavorRecord(self.session)
            return self.flavor_record
        return None
