"""Create configmgt tables

Revision ID: d07783bd94f
Revises: 1f714cccf0e7

"""

# revision identifiers, used by Alembic.
revision = 'd07783bd94f'
down_revision = '1f714cccf0e7'

from alembic import op
from sqlalchemy import text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.schema import (Column, ForeignKeyConstraint, Index,
                               PrimaryKeyConstraint, Sequence)
from sqlalchemy.types import (Boolean, Date, DateTime, Enum, Integer, String,
                              Text, Time)


def check_table_exists(table, schema='public'):
    sql = "SELECT EXISTS ( " \
            "SELECT 1 " \
            "FROM pg_tables " \
            "WHERE  schemaname = '" + schema + "' " \
            "AND tablename = '" + table + "')"

    result_proxy = op.get_bind().execute(sql)
    exists = result_proxy.fetchone()[0]

    return exists

def upgrade():
    if not check_table_exists('callback_list'):
        op.create_table(
            'callback_list',
            Column('uuid', UUID(as_uuid=True), nullable=False, server_default=text('uuid_generate_v4()')),
            Column('name', String(128), nullable=False),
            Column('queue_id', Integer, nullable=False),
            PrimaryKeyConstraint('uuid'),
        )

    if not check_table_exists('preferred_callback_period'):
        op.create_table(
            'preferred_callback_period',
            Column('uuid', UUID(as_uuid=True), nullable=False, server_default=text('uuid_generate_v4()')),
            Column('name', String(128), nullable=False, server_default=''),
            Column('period_start', Time, nullable=False),
            Column('period_end', Time, nullable=False),
            Column('default', Boolean, server_default='False'),
            PrimaryKeyConstraint('uuid'),
        )

    if not check_table_exists('callback_request'):
        sql_create_seq = """
            CREATE SEQUENCE callback_request_reference_number_seq
                START WITH 1
                INCREMENT BY 1
                NO MINVALUE
                NO MAXVALUE
                CACHE 1;
            """
        op.execute(sql_create_seq)
        
        reference_number_seq = Sequence('callback_request_reference_number_seq')
        op.create_table(
            'callback_request',
            Column('uuid', UUID(as_uuid=True), nullable=False, server_default=text('uuid_generate_v4()')),
            Column('list_uuid', UUID(as_uuid=True), nullable=False),
            Column('phone_number', String(40)),
            Column('mobile_phone_number', String(40)),
            Column('firstname', String(128)),
            Column('lastname', String(128)),
            Column('company', String(128)),
            Column('description', Text),
            Column('agent_id', Integer),
            Column('clotured', Boolean, server_default='False'),
            Column('preferred_callback_period_uuid', UUID(as_uuid=True)),
            Column('due_date', Date, nullable=False, server_default=text('now()')),
            Column('reference_number', Integer,
                                       reference_number_seq,
                                       server_default=reference_number_seq.next_value(),
                                       nullable=False),
            Column('voice_message_ref', String(128)),
            PrimaryKeyConstraint('uuid'),
            ForeignKeyConstraint(('list_uuid',),
                                ('callback_list.uuid',),),
            ForeignKeyConstraint(('preferred_callback_period_uuid',),
                                ('preferred_callback_period.uuid',),),
            Index('callback_request__idx_reference_number', 'reference_number'),
        )

    if not check_table_exists('users'):
            op.create_table(
            'users',
            Column('id', Integer, nullable=False),
            Column('login', String(64)),
            Column('type',Enum('admin', 'supervisor', 'teacher', name='user_type')),
            Column('validity_start', DateTime),
            Column('validity_end', DateTime),
            PrimaryKeyConstraint('id'),
        )

    if not check_table_exists('rights'):
        op.create_table(
            'rights',
            Column('id', Integer, nullable=False),
            Column('user_id', Integer, nullable=False),
            Column('category', Enum('queue', 'agentgroup', 'incall', 'recording_access', name='right_type'),
                    nullable=False),
            Column('category_id', Integer, nullable=False),
            PrimaryKeyConstraint('id'),
            ForeignKeyConstraint(('user_id',),
                                 ('users.id',),),
        )

    op.execute('CREATE SCHEMA IF NOT EXISTS xc')
    
    if not check_table_exists('queues', schema='xc'):
        op.create_table(
            'queues',
            Column('id', Integer, autoincrement=False, nullable=False),
            Column('name', String(128), nullable=False),
            Column('display_name', String(128), nullable=False),
            Column('number', String(128), nullable=False),
            PrimaryKeyConstraint('id'),
            schema='xc',
        )
    
    if not check_table_exists('users', schema='xc'):
        op.create_table(
            'users',
            Column('id', Integer, autoincrement=False, nullable=False),
            Column('login', String(64), nullable=False),
            Column('first_name', String(128), nullable=False),
            Column('last_name', String(128), nullable=False),
            PrimaryKeyConstraint('id'),
            schema='xc'
        )

    if not check_table_exists('queue_members_default', schema='xc'):
        op.create_table(
            'queue_members_default',
            Column('user_id', Integer, nullable=False),
            Column('queue_id', Integer, nullable=False),
            Column('penalty', Integer, nullable=False, server_default='0'),
            PrimaryKeyConstraint('user_id', 'queue_id', name='queue_members_default_pkey'),
            ForeignKeyConstraint(('user_id',),
                                 ('xc.users.id',),),
            ForeignKeyConstraint(('queue_id',),
                                 ('xc.queues.id',),),
            schema='xc'
        )


def downgrade():
    pass
