"""recurring_tasks

Revision: 0110
Revision ID: 1b7722f7b357
Revises: 50312a20c5ea
Create Date: 2018-01-12 10:50:50.264648

"""

revision = '1b7722f7b357'
down_revision = '50312a20c5ea'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

def upgrade():
    op.create_table('recurring_tasks',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('project_id', sa.Integer(), nullable=True),
    sa.Column('template_id', sa.Integer(), nullable=True),
    sa.Column('created_by_id', sa.Integer(), nullable=True),
    sa.Column('created_at', sa.DateTime(), nullable=True),
    sa.Column('updated_at', sa.DateTime(), nullable=True),
    sa.Column('recurring_days', sa.String(), nullable=True),
    sa.Column('recurring_time', sa.Time(), nullable=True),
    sa.Column('last_creation_at', sa.DateTime(), nullable=True),
    sa.ForeignKeyConstraint(['template_id'], ['cards.id'], ondelete='CASCADE'),
    sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ondelete='SET NULL'),
    sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ondelete='CASCADE'),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('recurring_task_groups',
    sa.Column('task_id', sa.Integer(), nullable=True),
    sa.Column('group_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['group_id'], ['card_groups.id'], ondelete='CASCADE'),
    sa.ForeignKeyConstraint(['task_id'], ['recurring_tasks.id'], ondelete='CASCADE')
    )
    op.create_index(op.f('ix_recurring_task_groups_group_id'), 'recurring_task_groups', ['group_id'], unique=False)
    op.create_index(op.f('ix_recurring_task_groups_task_id'), 'recurring_task_groups', ['task_id'], unique=False)
    op.create_index(op.f('ix_recurring_tasks_template_id'), 'recurring_tasks', ['template_id'], unique=False)
    op.create_index(op.f('ix_recurring_tasks_project_id'), 'recurring_tasks', ['project_id'], unique=False)
    cards = sa.Table('cards', sa.MetaData(), sa.Column('is_template', sa.Boolean))
    op.execute(cards.update().values(**{'is_template': False}))


def downgrade():
    op.execute("DELETE FROM cards WHERE is_template = TRUE")
    op.drop_index(op.f('ix_recurring_task_groups_task_id'), table_name='recurring_task_groups')
    op.drop_index(op.f('ix_recurring_task_groups_group_id'), table_name='recurring_task_groups')
    op.drop_table('recurring_task_groups')
    op.drop_index(op.f('ix_recurring_tasks_project_id'), table_name='recurring_tasks')
    op.drop_index(op.f('ix_recurring_tasks_template_id'), table_name='recurring_tasks')
    op.drop_table('recurring_tasks')
