"""create_qualification_tables

Revision ID: 581e85327dfa
Revises: 41c2e6de9334

"""

# revision identifiers, used by Alembic.
revision = '581e85327dfa'
down_revision = '41c2e6de9334'

from alembic import op
import sqlalchemy as sa

queue_table = sa.sql.table('queue')


def upgrade():
    op.create_table(
        'qualifications',
        sa.Column('id', sa.Integer),
        sa.Column('name', sa.String(128), nullable=False),
        sa.Column('active', sa.Integer, nullable=False, server_default='1'),
        sa.PrimaryKeyConstraint('id'),
    )

    op.create_table(
        'subqualifications',
        sa.Column('id', sa.Integer),
        sa.Column('name', sa.String(128), nullable=False),
        sa.Column('qualification_id', sa.Integer, nullable=False),
        sa.Column('active', sa.Integer, nullable=False, server_default='1'),
        sa.PrimaryKeyConstraint('id'),
        sa.ForeignKeyConstraint(['qualification_id'], ['qualifications.id'])
    )

    op.create_table(
        'queue_qualification',
        sa.Column('id', sa.Integer),
        sa.Column('queue_id', sa.Integer, nullable=False),
        sa.Column('qualification_id', sa.Integer, nullable=False),
        sa.PrimaryKeyConstraint('id')
    )

    op.create_table(
        'qualification_answers',
        sa.Column('id', sa.Integer),
        sa.Column('sub_qualification_id', sa.Integer),
        sa.Column('time', sa.DateTime, default=sa.func.current_timestamp()),
        sa.Column('callid', sa.String(128), nullable=False),
        sa.Column('agent', sa.Integer),
        sa.Column('queue', sa.Integer),
        sa.Column('first_name', sa.String(128), nullable=True),
        sa.Column('last_name', sa.String(128), nullable=True),
        sa.Column('comment', sa.String(255), nullable=True),
        sa.Column('custom_data', sa.Text, nullable=True),
        sa.PrimaryKeyConstraint('id')
    )

    op.execute('GRANT ALL PRIVILEGES ON TABLE qualifications TO configmgt')
    op.execute('GRANT ALL PRIVILEGES ON TABLE subqualifications TO configmgt')
    op.execute('GRANT ALL PRIVILEGES ON TABLE queue_qualification TO configmgt')
    op.execute('GRANT ALL PRIVILEGES ON TABLE qualification_answers TO configmgt')
    op.execute('GRANT ALL ON qualification_answers_id_seq  to configmgt')
    op.execute('GRANT ALL ON qualifications_id_seq to configmgt')
    op.execute('GRANT ALL ON subqualifications_id_seq to configmgt')
    op.execute('GRANT ALL ON queue_qualification_id_seq to configmgt')



def downgrade():
    op.drop_table('subqualifications')
    op.drop_table('qualifications')
    op.drop_table('queue_qualification')
    op.drop_table('qualification_answers')
