"""DispenseUE par semestre

Revision ID: 25e3ca6cc063
Revises: 7e5b519a27e1
Create Date: 2023-01-13 17:19:49.431591

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker  # added by ev


# revision identifiers, used by Alembic.
revision = "25e3ca6cc063"
down_revision = "7e5b519a27e1"
branch_labels = None
depends_on = None

Session = sessionmaker()


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "dispenseUE", sa.Column("formsemestre_id", sa.Integer(), nullable=True)
    )
    op.drop_constraint("dispenseUE_ue_id_etudid_key", "dispenseUE", type_="unique")
    op.create_index(
        op.f("ix_dispenseUE_formsemestre_id"),
        "dispenseUE",
        ["formsemestre_id"],
        unique=False,
    )
    op.create_unique_constraint(
        None, "dispenseUE", ["formsemestre_id", "ue_id", "etudid"]
    )
    op.create_foreign_key(
        None, "dispenseUE", "notes_formsemestre", ["formsemestre_id"], ["id"]
    )
    # ### end Alembic commands ###

    # Affecte les dispenses au formsemestre le plus récent ayant cette UE
    bind = op.get_bind()
    session = Session(bind=bind)
    dispenses = session.execute(
        sa.text(
            """SELECT id, ue_id, etudid FROM "dispenseUE" WHERE formsemestre_id IS NULL;"""
        )
    ).all()
    for dispense_id, ue_id, etudid in dispenses:
        formsemestre_ids = session.execute(
            sa.text(
                """
            SELECT notes_formsemestre.id
            FROM notes_formsemestre, notes_formations, notes_ue, notes_formsemestre_inscription
            WHERE notes_formsemestre.formation_id = notes_formations.id
            and notes_ue.formation_id = notes_formations.id
            and notes_ue.semestre_idx=notes_formsemestre.semestre_id
            and notes_formsemestre_inscription.formsemestre_id=notes_formsemestre.id
            and notes_ue.id = :ue_id
            and notes_formsemestre_inscription.etudid = :etudid
            ORDER BY notes_formsemestre.date_debut DESC
            LIMIT 1;
            """
            ),
            {"ue_id": ue_id, "etudid": etudid},
        ).all()
        if formsemestre_ids:
            formsemestre_id = formsemestre_ids[0][0]
            session.execute(
                sa.text(
                    """
                UPDATE "dispenseUE" SET formsemestre_id=:formsemestre_id WHERE id=:dispense_id"""
                ),
                {"formsemestre_id": formsemestre_id, "dispense_id": dispense_id},
            )


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        "dispenseUE_formsemestre_id_fkey", "dispenseUE", type_="foreignkey"
    )
    op.drop_constraint(
        "dispenseUE_formsemestre_id_ue_id_etudid_key", "dispenseUE", type_="unique"
    )
    op.drop_index(op.f("ix_dispenseUE_formsemestre_id"), table_name="dispenseUE")
    op.create_unique_constraint(
        "dispenseUE_ue_id_etudid_key", "dispenseUE", ["ue_id", "etudid"]
    )
    op.drop_column("dispenseUE", "formsemestre_id")
    # ### end Alembic commands ###