# -*- coding: utf-8 -*-
from ppms import ppms
from ppms.constants import DBMS_MSSQL
from ppms.migration import SQLPacket, PacketCategory, MaxVersionDependency

DROP_QUERY = """DROP INDEX UUID_DI_UNIQUE ON DT415"""
COUNT_QUERY = """SELECT COUNT(*) FROM sys.indexes WHERE name='UUID_DI_UNIQUE' AND object_id = OBJECT_ID('DT415')"""


class RemoveUniqueIndex(SQLPacket):
    """Remove a unique index in MSSQL"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 10454

    def get_dependencies(self):
        return (MaxVersionDependency('39.5.6'), )

    def fix(self, runner):
        db = ppms.db_get_dbms_name()
        if db != DBMS_MSSQL:
            self.log('Packet not required')
            return self.success()

        self.log('Checking if index exists: %s' % COUNT_QUERY)
        count = ppms.db_select(COUNT_QUERY)
        try:
            count = count[0][0]
        except IndexError:
            count = 0

        if count > 0:
            self.log('Index exists - dropping')
            self.modify_and_log(query=DROP_QUERY)
        else:
            self.log('Index doesn\'t exist - OK!')

        return self.success()