# https://itnext.io/setting-up-transactional-tests-with-pytest-and-sqlalchemy-b2d726347629

import pytest
import helpers

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

from app.models import Base, Tracks

DB_CONNECTION = "mysql+mysqldb://musicmuster_testing:musicmuster_testing@localhost/dev_musicmuster_testing"


@pytest.fixture(scope="session")
def db_engine():
    engine = create_engine(DB_CONNECTION, isolation_level="READ COMMITTED")
    Base.metadata.create_all(engine)
    yield engine
    engine.dispose()


@pytest.fixture(scope="function")
def session(db_engine):
    connection = db_engine.connect()
    transaction = connection.begin()
    sm = sessionmaker(bind=connection)
    session = scoped_session(sm)
    # print(f"PyTest SqlA: session acquired [{hex(id(session))}]")
    yield session
    # print(f" PyTest SqlA: session released and cleaned up [{hex(id(session))}]")
    session.remove()
    transaction.rollback()
    connection.close()


@pytest.fixture(scope="function")
def track1(session):
    track_path = "testdata/isa.mp3"
    metadata = helpers.get_file_metadata(track_path)
    track = Tracks(session, **metadata)
    return track


@pytest.fixture(scope="function")
def track2(session):
    track_path = "testdata/mom.mp3"
    metadata = helpers.get_file_metadata(track_path)
    track = Tracks(session, **metadata)
    return track
