"""top_level_card_attribute_group

Revision ID: 0259
Revises: 0258
Create Date: 2023-04-04 12:30:25.886437

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


# revision identifiers, used by Alembic.
revision = '0259'
down_revision = '0258'
branch_labels = None
depends_on = None


organizations = sa.Table(
    'organizations',
    sa.MetaData(),
    sa.Column('id', sa.Integer()),
    sa.Column('top_level_card_attribute_group_id', sa.Integer())
)

organization_members = sa.Table(
    'organization_members',
    sa.MetaData(),
    sa.Column('org_id', sa.Integer()),
    sa.Column('user_id', sa.Integer()),
    sa.Column('permission', sa.Integer())
)

users = sa.Table(
    'users',
    sa.MetaData(),
    sa.Column('id', sa.Integer()),
    sa.Column('locale', sa.String())
)

attribute_groups = sa.Table(
    'attribute_groups',
    sa.MetaData(),
    sa.Column('id', sa.Integer(), primary_key=True),
    sa.Column('owner_id', sa.Integer()),
    sa.Column('created_at', sa.DateTime()),
)

attributes = sa.Table(
    'attributes',
    sa.MetaData(),
    sa.Column('group_id', sa.Integer()),
    sa.Column('name', sa.String()),
    sa.Column('type_name', sa.String()),
    sa.Column('container', sa.String()),
    sa.Column('position', sa.Integer())
)

builtin_attributes = {
    'en': [
        {'name': 'Description', 'type': 'content', 'container': '__top__', 'position': 0},
        {'name': 'Due Date', 'type': 'date', 'position': 0}
    ],
    'fr': [
        {'name': 'Description', 'type': 'content', 'container': '__top__', 'position': 0},
        {'name': "Date d'échéance", 'type': 'date', 'position': 0}
    ],
    'es': [
        {'name': 'Descripción', 'type': 'content', 'container': '__top__', 'position': 0},
        {'name': "Fecha de vencimiento", 'type': 'date', 'position': 0}
    ],
    'de': [
        {'name': 'Beschreibung', 'type': 'content', 'container': '__top__', 'position': 0},
        {'name': "Fälligkeitsdatum", 'type': 'date', 'position': 0}
    ],
    'pt': [
        {'name': 'Descrição', 'type': 'content', 'container': '__top__', 'position': 0},
        {'name': "Data de vencimento", 'type': 'date', 'position': 0}
    ],
    'it': [
        {'name': 'Descrizione', 'type': 'content', 'container': '__top__', 'position': 0},
        {'name': "Data di scadenza", 'type': 'date', 'position': 0}
    ]
}


def upgrade():
    op.add_column('organizations', sa.Column('top_level_card_attribute_group_id', sa.Integer()))
    op.create_foreign_key(None, 'organizations', 'attribute_groups', ['top_level_card_attribute_group_id'], ['id'], ondelete='SET NULL')

    conn = op.get_bind()
    for org in conn.execute(organizations.select().order_by(organizations.c.id)):
        locale = conn.execute(sa.select([users.c.locale]).where(sa.and_(
            organization_members.c.org_id==org.id, organization_members.c.user_id==users.c.id,
            organization_members.c.permission==4))).scalar()
        if not locale:
            locale = 'en'
        r = conn.execute(attribute_groups.insert().values(owner_id=org.id, created_at=datetime.datetime.utcnow()))
        group_id = r.inserted_primary_key[0]
        conn.execute(organizations.update().where(organizations.c.id==org.id).values(top_level_card_attribute_group_id=group_id))
        for attr in builtin_attributes.get(locale, builtin_attributes['en']):
            conn.execute(attributes.insert().values(group_id=group_id, name=attr['name'], type_name=attr['type'],
                                                    container=attr.get('container'), position=attr['position']))


def downgrade():
    op.drop_column('organizations', 'top_level_card_attribute_group_id')
