# -*- coding: utf-8 -*-

from ppms import ppms
from ppms.migration.packet import *

class CustomerIndexCorrection(SQLPacket):
    '''Fix misconfigured indexes '''
    version = 1
    run_on_startup = True
    category = PacketCategory.CATEGORY_HELPER
    wi_number = 10594

    top_query = """SELECT DI000215, DI000239 FROM DT412 WHERE DI000275 = 0 AND DI002461 != 4 AND ENABLED = 1 AND DI000239 IN (SELECT DI000265 FROM DT415, DT420 WHERE (DT415.DI000266 = DT420.DI000289) AND DT415.ENABLED = 1 AND DT420.ENABLED = 1) GROUP BY DI000215, DI000239 HAVING(COUNT(DI000215) > 1)"""
    di_query = """SELECT DI000238, DI000215, DI000239, DI000242, DI002461 FROM DT412 WHERE DI000215 = '{1}' AND DI000239 = {0} ORDER BY DI002461"""
    change_index = """UPDATE DT412 SET DI000242 = {1} WHERE DI000238 = '{0}'"""

    def check_di_combo(self, table, di_name):
        dis = ppms.db_select(self.di_query.format(table, di_name))
        # The first parallel di should always be the 'real' (physical) DI. Test this

        if (dis[0][4] >= 2):
            self.log('Odd characteristics for column {1}, table {0}.'.format(table, di_name))
        else:
            # All parallel DIs should have the same index as their main (physical) DI
            index = dis[0][3]
            for i in range(1, len(dis)):
                if (dis[i][3] != index):
                    self.log("Changing DI index to {1} for di {0}".format(dis[1][0], index))
                    self.modify_and_log(self.change_index.format(dis[i][0], index))


    def fix(self, runner):
        multi_dis = ppms.db_select(self.top_query)
        for multi_di in multi_dis:
            self.check_di_combo(multi_di[1], multi_di[0])

        return self.success()
