"""clock_entry_breaks

Revision ID: d660db0ebc1b
Revises: 31351fc3f3e4
Create Date: 2017-06-29 08:29:01.539000

"""
import logging

from alembic import op, context
from sqlalchemy import (
    Boolean,
    Column,
    DateTime,
    ForeignKeyConstraint,
    String,

    inspect,
)
import sqlalchemy as sa

logger = logging.getLogger(__name__)

# revision identifiers, used by Alembic.
revision = 'd660db0ebc1b'
down_revision = u'8d1e358cc28b'
branch_labels = None
depends_on = None

first_agent_version = '17.7.3'


def upgrade():
    """
    Use batch-operations to support sqlite

    > with op.batch_alter_table('table_name') as batch_op:
    >     pass
    """

    tables = set()
    current_context = context.get_context()
    if current_context.connection:
        inspector = inspect(current_context.connection)
        tables = set(inspector.get_table_names())
    if 'clock_entry_breaks' in tables:
        logger.info("Table 'clock_entry_breaks' already exists. Skipping upgrade...")
        return
    op.create_table(
        'clock_entry_breaks',
        Column('id', String(64), primary_key=True),
        Column('clock_entry_id', String(32)),
        Column('start', DateTime, nullable=False),
        Column('end', DateTime, nullable=True),
        Column('paid', Boolean, nullable=False),
        ForeignKeyConstraint(
            ['clock_entry_id'],
            ['clock_entries.id'],
            name="fk_clock_entry_breaks_clock_entries",
        ),
    )


def downgrade():
    """
    Use batch-operations to support sqlite

    > with op.batch_alter_table('table_name') as batch_op:
    >     pass
    """

    tables = set()
    current_context = context.get_context()
    if current_context.connection:
        inspector = inspect(current_context.connection)
        tables = set(inspector.get_table_names())
    if 'clock_entry_breaks' not in tables:
        logger.info("Table 'clock_entry_breaks' does not exist. Skipping downgrade...")
        return
    op.drop_table('clock_entry_breaks')
