"""Add spacy_nlp_pipeline_models table

Revision ID: 31dd42e5ea6f
Revises: a3b727e3ff71
Create Date: 2022-10-13 12:47:50.870474

"""
from alembic import op
import shutil
import sqlalchemy as sa
import os
from app.models import User


# revision identifiers, used by Alembic.
revision = '31dd42e5ea6f'
down_revision = 'a3b727e3ff71'
branch_labels = None
depends_on = None


def upgrade():
    for user in User.query.all():
        spacy_nlp_pipeline_models_dir = os.path.join(user.path, 'spacy_nlp_pipeline_models')
        if os.path.exists(spacy_nlp_pipeline_models_dir):
            if not os.path.isdir(spacy_nlp_pipeline_models_dir):
                raise OSError(f'Not a directory: {spacy_nlp_pipeline_models_dir}')
            if not os.listdir(spacy_nlp_pipeline_models_dir):
                raise OSError(f'Directory not empty: {spacy_nlp_pipeline_models_dir}')
        else:
            os.mkdir(spacy_nlp_pipeline_models_dir)


    op.create_table(
        'spacy_nlp_pipeline_models',
        sa.Column('creation_date', sa.DateTime(), nullable=True),
        sa.Column('filename', sa.String(length=255), nullable=True),
        sa.Column('last_edited_date', sa.DateTime(), nullable=True),
        sa.Column('mimetype', sa.String(length=255), nullable=True),
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('user_id', sa.Integer(), nullable=True),
        sa.Column('title', sa.String(length=64), nullable=True),
        sa.Column('description', sa.String(length=255), nullable=True),
        sa.Column('version', sa.String(length=16), nullable=True),
        sa.Column('compatible_service_versions', sa.String(length=255), nullable=True),
        sa.Column('publisher', sa.String(length=128), nullable=True),
        sa.Column('publisher_url', sa.String(length=512), nullable=True),
        sa.Column('publishing_url', sa.String(length=512), nullable=True),
        sa.Column('publishing_year', sa.Integer(), nullable=True),
        sa.Column('shared', sa.Boolean(), nullable=True),
        sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
        sa.PrimaryKeyConstraint('id')
    )


def downgrade():
    for user in User.query.all():
        spacy_nlp_pipeline_models_dir = os.path.join(user.path, 'spacy_nlp_pipeline_models')
        if os.path.exists(spacy_nlp_pipeline_models_dir):
            shutil.rmtree(spacy_nlp_pipeline_models_dir)


    op.drop_table('spacy_nlp_pipeline_models')
