from contextlib import contextmanager

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
# from sqlalchemy.orm import Session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.scoping import scoped_session

from core import constants

engine = create_engine(
    f'sqlite:///{constants.DB_PATH}',
    connect_args={'check_same_thread': False},
    echo=constants.SQL_ALCHEMY_VERBOSE)
Base = declarative_base()

session_factory = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Session = scoped_session(session_factory)


def create():
    if constants.DB_PATH.exists():
        raise FileExistsError('A db file already exists')
    Base.metadata.create_all(engine)


def close():
    Session.remove()
    engine.dispose()
