"""make xivo xivocc ready

Revision ID: 4008f033a789
Revises: 145d2e976e29

"""

# revision identifiers, used by Alembic.
revision = '4008f033a789'
down_revision = '145d2e976e29'

from alembic import op
from xivo_db import postgres


def upgrade():
    create_user_stats()
    op.execute("GRANT SELECT ON ALL TABLES IN SCHEMA PUBLIC TO stats")

    op.execute("""
        DO $$
        BEGIN
            IF NOT EXISTS (SELECT 1 FROM func_key_template WHERE id = (SELECT func_key_private_template_id FROM userfeatures WHERE loginclient = 'xuc'))
            THEN
                INSERT INTO "func_key_template"
                    (name, private)
                SELECT
                    'xuc technical', 'true';
            ELSE
                UPDATE "func_key_template"
                SET (name, private) = ('xuc technical', 'true')
                WHERE id = (SELECT func_key_private_template_id FROM userfeatures WHERE loginclient = 'xuc');
            END IF;
        END;
        $$
    """)
    op.execute("""
        DO $$
        BEGIN
            IF NOT EXISTS (SELECT 1 FROM "userfeatures" WHERE loginclient = 'xuc')
            THEN
                INSERT INTO "userfeatures"
                    (uuid, firstname, email, agentid, pictureid, entityid, callerid, ringseconds, simultcalls,
                    enableclient, loginclient, passwdclient, cti_profile_id, enablehint, enablevoicemail, enablexfer,
                    enableonlinerec, callrecord, incallfilter, enablednd, enableunc, destunc, enablerna, destrna,
                    enablebusy, destbusy, musiconhold, outcallerid, mobilephonenumber, bsfilter, preprocess_subroutine,
                    timezone, language, ringintern, ringextern, ringgroup, ringforward, rightcallcode, commented,
                    func_key_private_template_id, lastname, userfield, description)
                SELECT
                    'd5dd4e90-c6ce-4b0e-a85f-419ae3cc3561', 'xuc', '', 0, 0, (SELECT id FROM entity LIMIT 1), 'xuc', 30, 5,
                    1, 'xuc', '0000', (SELECT id FROM cti_profile LIMIT 1), 1, 0, 1,
                    0, 0, 0, 0, 0, '', 0, '',
                    0, '', 'default', 'default', '', 'no', '',
                    '', '', '', '', '', '', '', 0,
                    (SELECT id FROM func_key_template WHERE name = 'xuc technical' LIMIT 1), 'technical', '', '';
            ELSE
                UPDATE "userfeatures"
                SET (firstname, lastname) = ('xuc', 'technical')
                WHERE loginclient = 'xuc';
            END IF;
        END;
        $$
    """)

def downgrade():
    pass


def create_user_stats():
    db_user = 'stats'
    db_user_password = 'stats'

    conn = postgres.create_db_connection()
    postgres.create_user(conn, db_user, db_user_password)
