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


class ShowConcurrentDAUsages(SQLPacket):
    """Logs all modules which have data areas 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 = 19439

    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, DI000969 from DT406
            join DT515 on (DT406.DI000970=DT515.DI010327)
            join DT513 on (DT515.DI010325=DT513.DI010324)
            where DI000969 in (select DI000969 from DT406 da_mod
                                where da_mod.DI000970 = DT406.DI000970
                                and da_mod.DI000971 != DT406.DI000971)

            and DI000982 != 0 -- pos !=0
            and (DI025596 like '39' or DI025596 like '39PM')   -- Arbeitsgebiet release =39 oder 39PM
            and DI010324 != '01100186'
            group by DI000970, DI000969
            union
            -- custom modules
            select DI000970, DI000969 from DT406
            where DI000978 = '{sys_lic}'
            and DI000969 in (select DI000969 from DT406 da_mod
                                where da_mod.DI000970 = DT406.DI000970
                                and da_mod.DI000971 != DT406.DI000971)
            and DI000982 != 0
            group by DI000970, DI000969
            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_id = row
                try:
                    modules[mod_id].append(da_id)
                except KeyError:
                    modules[mod_id] = [da_id]

            for mod_id, da_ids in modules.items():
                self.log('Module {mod_id} '
                         'has multiple DAs: {da_id}.'.format(mod_id=mod_id,
                                                           da_id=', '.join(str(x) for x in da_ids)))

            return self.fail()