"""public_role

Revision: 0121
Revision ID: 3cb0832a6d79
Revises: 5555e993377c
Create Date: 2018-03-30 15:41:27.520322

"""

# revision identifiers, used by Alembic.
revision = '3cb0832a6d79'
down_revision = '5555e993377c'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


orgs = sa.Table(
    'organizations',
    sa.MetaData(),
    sa.Column('id', sa.Integer()),
    sa.Column('default_public_role_id', sa.Integer()),
    sa.Column('default_guest_role_id', sa.Integer())
)

projects = sa.Table(
    'projects',
    sa.MetaData(),
    sa.Column('id', sa.Integer()),
    sa.Column('owner_id', sa.Integer()),
    sa.Column('public_permission', sa.Integer()),
    sa.Column('is_public', sa.Boolean()),
    sa.Column('public_role_id', sa.Integer())
)

roles = sa.Table(
    'roles',
    sa.MetaData(),
    sa.Column('id', sa.Integer()),
    sa.Column('owner_id', sa.Integer()),
    sa.Column('builtin', sa.String())
)

def upgrade():
    conn = op.get_bind()

    op.add_column('organizations', sa.Column('default_public_role_id', sa.Integer(), nullable=True))
    op.add_column('organizations', sa.Column('default_guest_role_id', sa.Integer(), nullable=True))
    op.create_foreign_key('organizations_default_public_role_id_fkey', 'organizations', 'roles', ['default_public_role_id'], ['id'], ondelete='SET NULL')
    op.create_foreign_key('organizations_default_guest_role_id_fkey', 'organizations', 'roles', ['default_guest_role_id'], ['id'], ondelete='SET NULL')

    op.add_column('projects', sa.Column('is_public', sa.Boolean(), nullable=True))
    op.add_column('projects', sa.Column('public_role_id', sa.Integer(), nullable=True))
    op.create_foreign_key('projects_public_role_id_fkey', 'projects', 'roles', ['public_role_id'], ['id'], ondelete='SET NULL')

    for org in conn.execute(orgs.select()):
        role = conn.execute(roles.select().where(sa.and_(roles.c.owner_id == org.id, roles.c.builtin == 'OBSERVER'))).first()
        conn.execute(orgs.update().where(orgs.c.id == org.id).values(
            default_public_role_id=role.id if role else None,
            default_guest_role_id=role.id if role else None))

    conn.execute(projects.update().where(projects.c.public_permission==0).values(is_public=False))
    for project in conn.execute(projects.select().where(projects.c.public_permission > 0)):
        builtin = 'OBSERVER'
        if project.public_permission == 2:
            builtin = 'OBSERVER ALLOWED TO COMMENT'
        elif project.public_permission == 3:
            builtin = 'MEMBER'
        role = conn.execute(roles.select().where(sa.and_(roles.c.owner_id == project.owner_id, roles.c.builtin == builtin))).first()
        conn.execute(projects.update().where(projects.c.id == project.id).values(is_public=True, public_role_id=role.id if role else None))


def downgrade():
    op.drop_column('projects', 'public_role_id')
    op.drop_column('projects', 'is_public')
