"""add blog_post.slug

Revision ID: 820bb005f2c5
Revises: <PASSWORD>
Create Date: 2016-06-09 22:15:53.127614

"""

# revision identifiers, used by Alembic.
revision = '820bb005f2c5'
down_revision = '15ab4487a<PASSWORD>'

import re

from alembic import op
from sqlalchemy.orm import sessionmaker
import sqlalchemy as sa
from sqlalchemy import text

from blag.models import BlogPost

non_ascii = re.compile(r'[^a-zA-Z-]*')

def slugify(title):
    return non_ascii.sub('', title.lower().replace(' ', '-'))


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('blog_post', sa.Column('slug', sa.String(length=40), nullable=True))
    # year = func.year(BlogPost.datetime_added)
    year = text("date_trunc('year', blog_post.datetime_added)")

    op.create_index(op.f('ix_blog_post_slug'), 'blog_post', [year, 'slug'], unique=False)

    # Add a default slug for existing blog posts
    connection = op.get_bind()
    SessionMaker = sessionmaker(bind=connection.engine)
    session = SessionMaker(bind=connection)
    for blog_post in session.query(BlogPost):
        blog_post.slug = slugify(blog_post.title)

    session.flush()

    # Mark slug as not nullable
    op.alter_column('blog_post', 'slug', nullable=False)
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_blog_post_slug'), table_name='blog_post')
    op.drop_column('blog_post', 'slug')
    ### end Alembic commands ###
