"""form_improvements

Revision: 0147
Revision ID: 44e27652773
Revises: 51e932e2e7f7
Create Date: 2018-08-13 16:09:06.001424

"""

# revision identifiers, used by Alembic.
revision = '44e27652773'
down_revision = '51e932e2e7f7'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.add_column('request_forms', sa.Column('background_image_filename', sa.String(), nullable=True))
    op.add_column('request_forms', sa.Column('header_color', sa.String(), nullable=True))
    op.add_column('request_forms', sa.Column('send_confirmation_email', sa.Boolean(), nullable=True))

    op.add_column('request_form_fields', sa.Column('position', sa.Integer(), nullable=True))
    op.add_column('request_form_fields', sa.Column('field_type', sa.String(), nullable=True))
    op.add_column('request_form_fields', sa.Column('image_filename', sa.String(), nullable=True))

    op.execute("UPDATE request_forms SET send_confirmation_email = true")

    op.execute("""
        WITH positions as (
            SELECT id, row_number() OVER (partition by request_form_id order by id) AS p
            FROM request_form_fields
        ) UPDATE request_form_fields SET field_type = 'attribute', position = positions.p - 1 FROM positions
        WHERE request_form_fields.id = positions.id
    """)


def downgrade():
    op.drop_column('request_forms', 'background_image_filename')
    op.drop_column('request_forms', 'header_color')
    op.drop_column('request_forms', 'send_confirmation_email')

    op.drop_column('request_form_fields', 'position')
    op.drop_column('request_form_fields', 'field_type')
    op.drop_column('request_form_fields', 'image_filename')
