from folkugat_web.dal.sql import get_connection
from folkugat_web.dal.sql.playlists import write as playlists_w
from folkugat_web.dal.sql.playlists.ddl import (create_playlist_entries_table,
                                                create_playlists_table)
from folkugat_web.dal.sql.sessions import playlists as session_playlists
from folkugat_web.dal.sql.sessions import query as sessions_q
from folkugat_web.dal.sql.sessions.ddl import create_session_playlists_table
from folkugat_web.model.playlists import PlaylistType

with get_connection() as con:
    cur = con.cursor()

    drop_query = """DROP TABLE rehearse_data"""
    _ = cur.execute(drop_query)

    alter_query = """ALTER TABLE playlists RENAME TO playlists_old"""
    _ = cur.execute(alter_query)

    # Create new tables
    create_playlist_entries_table(con=con)
    create_playlists_table(con=con)
    create_session_playlists_table(con=con)

    # Create new playlists
    sessions = sessions_q.get_sessions(con=con)
    for session in sessions:
        if session.id is None:
            raise ValueError("Session without id!")

        setlist_id = playlists_w.create_playlist(con=con)
        session_playlists.insert_playlist(
            session_id=session.id,
            playlist_type=PlaylistType.SESSION_SETLIST,
            playlist_id=setlist_id,
            con=con,
        )

        slowjam_id = playlists_w.create_playlist(con=con)
        session_playlists.insert_playlist(
            session_id=session.id,
            playlist_type=PlaylistType.SESSION_SLOWJAM,
            playlist_id=slowjam_id,
            con=con,
        )

    # Migrate
    migrate_query = """
        INSERT INTO playlist_entries
          (id, playlist_id, set_id, tema_id)
        SELECT
          NULL, sp.playlist_id, pl_old.set_id, pl_old.tema_id
        FROM playlists_old pl_old JOIN session_playlists sp USING (session_id)
        WHERE sp.playlist_type = "session_setlist"
    """
    _ = cur.execute(migrate_query)

print("DONE!")
