# coding=utf-8

from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from etc import SQLARCHEMY
from utils import getLogger

logger = getLogger(__name__)
engine = create_engine(SQLARCHEMY.database,
                       pool_size=SQLARCHEMY.pool,
                       max_overflow=SQLARCHEMY.max_overflow,
                       pool_timeout=SQLARCHEMY.pool_timeout,
                       pool_pre_ping=SQLARCHEMY.pool_pre_ping)
DBSession = sessionmaker(bind=engine)

session = DBSession()


@contextmanager
def session_maker(session=session):
    try:
        yield session
        session.commit()
    except Exception as e:
        logger.debug(e)
        session.rollback()
        raise
    finally:
        session.close()


def save_data(model_list):
    with session_maker() as db_session:
        if model_list:
            db_session.add(model_list[0])

        #     db_session.add_all(model_list)
        # else:
        #     db_session.close()
