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

from ppms.migration import SQLPacket, PacketCategory, MinVersionDependency, MaxVersionDependency, ChangeDTPPacket


MODULES = "('009CF5')"

DELETE_STATEMENTS = [# MCU
                     "DELETE FROM DT435 WHERE DI023517 = '010200' AND DI001538 IN (SELECT DI010200 FROM DT411 WHERE "
                     "DI000306 IN (SELECT DI000969 FROM DT406 WHERE DI000970 IN %s))" % MODULES,
                     "DELETE FROM DT435 WHERE DI023517 IN ('001589', '029710') AND DI001538 IN ((SELECT DI001589 "
                     "FROM "
                     "DT410 WHERE DI000198 IN (SELECT DI000969 FROM DT406 WHERE DI000970 IN %s)) UNION (SELECT "
                     "DI029710 "
                     "FROM DT410 WHERE DI000198 IN (SELECT DI000969 FROM DT406 WHERE DI000970 IN %s)))" % (
                         MODULES, MODULES),
                     "DELETE FROM DT435 WHERE DI023517 IN ('001588') AND DI001538 IN (SELECT DI001588 FROM DT405 "
                     "WHERE DI000123 IN %s)" % MODULES,
                     "DELETE FROM DT435 WHERE DI023517 IN ('057816') AND DI001538 IN (SELECT DI057816 FROM DT405 "
                     "WHERE DI000123 IN %s)" % MODULES,
                     "DELETE FROM DT411 WHERE DI000306 IN (SELECT DI000969 FROM DT406 WHERE DI000970 IN %s)" %
                     MODULES,
                     "DELETE FROM DT410 WHERE DI000198 IN (SELECT DI000969 FROM DT406 WHERE DI000970 IN %s)" %
                     MODULES,
                     "DELETE FROM DT406 WHERE DI000970 IN %s" % MODULES,
                     "DELETE FROM DT404 WHERE DI028100 IN %s OR DI028040 IN %s" % (MODULES, MODULES),
                     "DELETE FROM DT405 WHERE DI000123 IN %s" % MODULES,
]


class ReplaceHelperPacketModuleCustomizing(SQLPacket, ChangeDTPPacket):
    """Replace the old helper packet module with the new one"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 16668

    FILENAME = 'wi16668_helper_module.sql'

    def get_dependencies(self):
        return (MinVersionDependency(version='39.4'),
                MaxVersionDependency(version='39.4'))

    def fix(self, packet_runner):
        self.log('Wipe old migration framework components')
        for statement in DELETE_STATEMENTS:
            self.modify_and_log(query=statement)

        self.log('Import new migration framework components')
        self.apply_dml_file(self.sql_planta_de_dbms, self.FILENAME)

        return self.success()