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


class ShowConcurrentDAPos(SQLPacket):
    """Logs all modules which have data area positions which are used more than
    once - which pretends that the module can start. """
    done_after_success = False
    run_on_startup = False
    category = PacketCategory.CATEGORY_HELPER
    wi_number = 18692


    def fix(self, packet_runner):
        sys_lic = ppms.uvar_get('@3')
        get_da_list = """select
            -- 39 standard modules which have been changed in
            -- the customer's system
            DI000970, DI000982 from DT406
            join DT515 on (DT406.DI000970=DT515.DI010327)
            join DT513 on (DT515.DI010325=DT513.DI010324)
            where DI000982 in (select DI000982 from DT406 da_mod
                                where da_mod.DI000970 = DT406.DI000970
                                and da_mod.DI000969 != DT406.DI000969)
            and DI000982 != 0
            and (DI025596 like '39' or DI025596 like '39PM')
            and DI010324 != '01100186'
            group by DI000970, DI000982
            union all
            -- custom modules
            select DI000970, DI000982 from DT406
            where DI000978 = '{sys_lic}'
            and DI000982 in (select DI000982 from DT406 da_mod
                              where da_mod.DI000970 = DT406.DI000970
                              and da_mod.DI000969 != DT406.DI000969)
            and DI000982 != 0
            group by DI000970, DI000982
            order by DI000970""".format(**locals())
        multi_used_positions = self.select_and_log(get_da_list)

        if not multi_used_positions:
            self.log('No problematic modules were found.')
            return self.success()
        else:
            modules = {}
            for row in multi_used_positions:
                mod_id, da_pos = row
                da_pos = int(round(da_pos,0))
                try:
                    modules[mod_id].append(da_pos)
                except KeyError:
                    modules[mod_id] = [da_pos]

            for mod_id, shared_positions in modules.items():
                self.log('Module {mod_id} has multiple DAs using '
                         'position(s) {pos}.'.format(mod_id=mod_id,pos=', '.join(str(x) for x in shared_positions)))

            return self.fail()