# Copyright (C) 2019-2020, Therapixel SA.
# All rights reserved.
# This file is subject to the terms and conditions described in the
# LICENSE file distributed in this package.
"""Initial configuration

Revision ID: eef30b8456eb
Revises:
Create Date: 2021-11-14 10:59:37.202433

"""
import sqlalchemy as sa

from alembic import op

from pacsanini.db.migrate import ReplaceableObject, table_exists
from pacsanini.db.views import (
    MANUFACTURER_VIEW_SELECT,
    STUDY_META_VIEW_SELECT,
    ManufacturerView,
    StudyMetaView,
)


# revision identifiers, used by Alembic.
# pylint: disable=invalid-name
revision = "eef30b8456eb"
down_revision = None
branch_labels = None
depends_on = None

study_meta_view = ReplaceableObject(
    StudyMetaView.__tablename__, str(STUDY_META_VIEW_SELECT)
)
manufacturer_view = ReplaceableObject(
    ManufacturerView.__tablename__, str(MANUFACTURER_VIEW_SELECT)
)


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    if not table_exists("patients"):
        op.create_table(
            "patients",
            sa.Column("id", sa.Integer(), nullable=False),
            sa.Column("patient_id", sa.String(), nullable=True),
            sa.Column("patient_name", sa.String(), nullable=True),
            sa.Column("patient_birth_date", sa.DateTime(), nullable=True),
            sa.Column("institution", sa.String(), nullable=True),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("patient_id"),
        )
    if not table_exists("studies_find"):
        op.create_table(
            "studies_find",
            sa.Column("id", sa.Integer(), nullable=False),
            sa.Column("patient_name", sa.String(), nullable=True),
            sa.Column("patient_id", sa.String(), nullable=True),
            sa.Column("study_uid", sa.String(), nullable=True),
            sa.Column("study_date", sa.DateTime(), nullable=True),
            sa.Column("accession_number", sa.String(), nullable=True),
            sa.Column("retrieved_on", sa.DateTime(), nullable=True),
            sa.Column("found_on", sa.DateTime(), nullable=True),
            sa.PrimaryKeyConstraint("id"),
        )
        op.create_index(
            op.f("ix_studies_find_study_uid"),
            "studies_find",
            ["study_uid"],
            unique=True,
        )
    if not table_exists("studies"):
        op.create_table(
            "studies",
            sa.Column("id", sa.Integer(), nullable=False),
            sa.Column("study_find_id", sa.Integer(), nullable=True),
            sa.Column("patient_id", sa.Integer(), nullable=True),
            sa.Column("study_uid", sa.String(), nullable=True),
            sa.Column("study_date", sa.DateTime(), nullable=True),
            sa.Column("patient_age", sa.Integer(), nullable=True),
            sa.Column("accession_number", sa.String(), nullable=True),
            sa.ForeignKeyConstraint(["patient_id"], ["patients.id"]),
            sa.ForeignKeyConstraint(["study_find_id"], ["studies_find.id"]),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("study_uid"),
        )
    if not table_exists("series"):
        op.create_table(
            "series",
            sa.Column("id", sa.Integer(), nullable=False),
            sa.Column("study_id", sa.Integer(), nullable=True),
            sa.Column("series_uid", sa.String(), nullable=True),
            sa.Column("modality", sa.String(), nullable=True),
            sa.ForeignKeyConstraint(["study_id"], ["studies.id"]),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("series_uid"),
        )
    if not table_exists("images"):
        op.create_table(
            "images",
            sa.Column("id", sa.Integer(), nullable=False),
            sa.Column("series_id", sa.Integer(), nullable=True),
            sa.Column("institution", sa.String(), nullable=True),
            sa.Column("patient_id", sa.String(), nullable=True),
            sa.Column("patient_name", sa.String(), nullable=True),
            sa.Column("study_uid", sa.String(), nullable=True),
            sa.Column("study_date", sa.DateTime(), nullable=True),
            sa.Column("series_uid", sa.String(), nullable=True),
            sa.Column("modality", sa.String(), nullable=True),
            sa.Column("sop_class_uid", sa.String(), nullable=True),
            sa.Column("image_uid", sa.String(), nullable=True),
            sa.Column("acquisition_time", sa.Float(), nullable=True),
            sa.Column("manufacturer", sa.String(), nullable=True),
            sa.Column("manufacturer_model_name", sa.String(), nullable=True),
            sa.Column("meta", sa.JSON(), nullable=True),
            sa.Column("filepath", sa.String(), nullable=True),
            sa.ForeignKeyConstraint(["series_id"], ["series.id"]),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("image_uid"),
        )
        op.create_index(
            op.f("ix_images_patient_id"), "images", ["patient_id"], unique=False
        )
        op.create_index(
            op.f("ix_images_study_uid"), "images", ["study_uid"], unique=False
        )

    # ### added custom commands ###
    if not table_exists("alembic_version"):
        op.create_table(
            "alembic_version",
            sa.Column("version_num", sa.String(32), nullable=False),
            sa.PrimaryKeyConstraint("version_num"),
            sa.UniqueConstraint("version_num"),
        )
        bind = op.get_bind()
        engine = bind.engine
        engine.execute(
            "INSERT INTO alembic_version (version_num,) VALUES (:version_num, )",
            version_num=revision,
        )
    if not table_exists(study_meta_view.name):
        op.create_view(study_meta_view)
    if not table_exists(manufacturer_view.name):
        op.create_view(manufacturer_view)
    # ### end custom commands ###
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f("ix_images_study_uid"), table_name="images")
    op.drop_index(op.f("ix_images_patient_id"), table_name="images")
    op.drop_table("images")
    op.drop_table("series")
    op.drop_table("studies")
    op.drop_index(op.f("ix_studies_find_study_uid"), table_name="studies_find")
    op.drop_table("studies_find")
    op.drop_table("patients")

    # ### added custom commands ###
    op.drop_view(study_meta_view)
    op.drop_view(manufacturer_view)
    # ### end custom commands ###
    # ### end Alembic commands ###
