"""add end_points and hosts tables

Revision ID: 1414da92b3ca
Revises: 42185d6d93cb
Create Date: 2015-04-20 11:49:17.783924

"""

# revision identifiers, used by Alembic.
revision = '1414da92b3ca'
down_revision = '42185d6d93cb'

from alembic import op
import sqlalchemy as sa


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('end_point',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.Text(), nullable=False, unique=True),
    sa.Column('default', sa.Boolean(), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )

    op.create_table('host',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('value', sa.Text(), nullable=False),
    sa.Column('end_point_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['end_point_id'], ['end_point.id'], ),
    sa.PrimaryKeyConstraint('id')
    )


    op.add_column(u'user', sa.Column('end_point_id', sa.Integer(), nullable=True))
    op.create_unique_constraint('user_email_end_point_idx', 'user', ['email', 'end_point_id'])
    op.create_unique_constraint('user_login_end_point_idx', 'user', ['login', 'end_point_id'])
    op.drop_constraint(u'user_email_key', 'user')
    op.drop_constraint(u'user_login_key', 'user')

    op.execute("INSERT INTO end_point VALUES (DEFAULT, 'navitia.io', true);")
    op.execute('UPDATE "user" set end_point_id=(select id from end_point);')
    op.alter_column(u'user', 'end_point_id', nullable=True)

    ### end Alembic commands ###



def downgrade():
    #remove old user affected to another endpoint
    op.execute('delete from "user" where end_point_id != 1;')
    op.create_unique_constraint(u'user_login_key', 'user', ['login'])
    op.create_unique_constraint(u'user_email_key', 'user', ['email'])
    op.drop_constraint('user_login_end_point_idx', 'user')
    op.drop_constraint('user_email_end_point_idx', 'user')
    op.drop_column(u'user', 'end_point_id')
    op.drop_table('host')
    op.drop_table('end_point')
    ### end Alembic commands ###
