import logging
import hashlib

from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.orm import mapper
from sqlalchemy.engine import create_engine
from sqlalchemy.engine.url import URL

from orangescape.model.server.sql.SqlUtil import ATTACHMENT_TBL_NAME

import appconfig as config

from orangescape.model.server.util.ServerUtil import _get_class

DATABASE_NAME = config.SQL_SCHEMA
engine = create_engine(URL('mysql+googledialect', database=DATABASE_NAME, username='root', password='root'),instance=config.SQL_INSTANCE, paramstyle='format', echo=False, pool_recycle=300)

"""For local testcase"""
#DATABASE_NAME = 'buildtest'
#engine = create_engine(URL('mysql', host='localhost', database=DATABASE_NAME, username='root', password='root'), echo=False)

Session = None
def makeSession():
    global Session
    logging.info('Creating session using sessionmaker')
#    Session = scoped_session(sessionmaker())
#    Session.configure(bind = engine, expire_on_commit=False)
    Session = sessionmaker(bind=engine, expire_on_commit=False)

makeSession()

from orangescape.model.server.Context import getApplication
metadataContext = getApplication()

__orm_metadata__ = None
__attachment_mapping__ = None

def getMappedClass(metadata):
    modPath  = 'orangescape.model.server.sql.classes.temp%s'%(metadata.getSheetName())
    return _get_class(modPath)

def getTblMappedClass(metadata):
    modPath  = 'orangescape.model.server.sql.classes.tbl%s'%(metadata.getSheetName())
    return _get_class(modPath)

def getAttachmentClass():
    modPath  = 'orangescape.model.server.sql.classes.Attachment'
    return _get_class(modPath)
