# -*- coding: utf-8 -*-
from ppms.migration import SQLPacket, PacketCategory, MigratePythonPacket, ChangeDTPPacket, MaxVersionDependency, VersionType, PacketDependency, PacketState


PACKET_PATH_A = r'migration.hotfix.S_39_5_11.wi12687_new_migration_packets.A_PortMigrationPackets'
PACKET_PATH_B = r'migration.hotfix.S_39_5_11.wi12687_new_migration_packets.B_UpdateLastStateDataitem'
PACKET_PATH_C = r'migration.hotfix.S_39_5_11.wi12687_new_migration_packets.C_PortMigrationValueranges'

VALUERANGES = {'062196': ('cb3f84693a66958f82c92193459da505', 'c3fc18a90780ce2efd57a8a04ac16b5f', """from ppms.migration import get_packet_instance_from_path

def computeOutput(di):
    dtp_record = di.get_dtp_record()

    path = dtp_record.pythonpath.get_value()
    uuid = dtp_record.uuid.get_value()

    packet = get_packet_instance_from_path(path=path, uuid=uuid)
    return packet.last_state

computeOutput.deps = ('DI062155', 'DI062142', 'DI062201')"""),
               '062200': ('7696c572062082360e7d1761f8199f6e', '6085d678a34d29ffd033fc4ef2c1bb23', """from ppms.migration import PacketState, get_last_packet_history_rec

STATE_TO_OLE = {PacketState.NEW: 'DBOLE(001248)',
                PacketState.INSTALLED: 'DBOLE(001243)',
                PacketState.SKIPPED: 'DBOLE(001247)',
                PacketState.FAILED: 'DBOLE(001245)'}

def computeOutput(di):
    dtp_record = di.get_dtp_record()

    last_status = dtp_record.last_status.get_value()

    return STATE_TO_OLE.get(last_status, 'DBOLE(001248)')

computeOutput.deps = ('DI062196', )"""),
               '062326': ('f9aa5eec66d6714ff2fa2e6bed46aa07', '34dcfa8cda697461668fe0203594ee01', """from ppms.migration import PacketCategory, get_packet_instance_from_path

def get_text_constant(const_id):
    record = ppms.search_record(425, [const_id], [296], True)
    if record:
        return record.get_di_by_id(296).get_value()

    return ''


CATEGORY_TO_TEXT = {PacketCategory.CATEGORY_OPTIONAL: get_text_constant('001573'),
                    PacketCategory.CATEGORY_MANDATORY: get_text_constant('001574'),
                    PacketCategory.CATEGORY_HELPER: get_text_constant('001575')}

def computeOutput(di):
    dtp_record = di.get_dtp_record()
    category = dtp_record.packet_category_number.get_value()

    return CATEGORY_TO_TEXT[category]

computeOutput.deps = ('DI063232', )""")}


class A_PortMigrationPackets(SQLPacket):
    """Insert all the sql objects related to the new migration packets"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12687

    FILENAME = 'wi12687_new_migration_packets.sql'

    def get_dependencies(self):
        return (MaxVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),)

    def fix(self, runner):
        self.apply_dml_file(self.sql_planta_de_dbms, self.FILENAME)

        return self.success()


class B_UpdateLastStateDataitem(ChangeDTPPacket):
    """Change the type of DI 062196

    It should be changed from Alpha 20 to a Number with a length of 6
    """
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12687

    def get_dependencies(self):
        return (PacketDependency(packet_path=PACKET_PATH_A, expected_state=PacketState.INSTALLED),
                MaxVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING))

    def fix(self, runner):
        values = (('column_type', (5, 21)),
                  ('df_type', ('AL', 'N')),
                  ('ppms_type', ('AL', 'N4')),
                  ('db_typ', ('X', 'N4')),
                  ('db_length', (20, 6)),
                  ('df_length', (20, 6)))

        record = self.get_record(dt_num=412, key_list=['062196'], di_list=[value[0] for value in values])

        failures = 0

        for python_id, (old_value, new_value) in values:
            if not self.change_value(record=record, attribute=python_id, old_value=old_value, new_value=new_value):
                failures += 1

        if failures:
            return self.fail('Could not update all attributes')

        return self.success()


class C_PortMigrationValueranges(MigratePythonPacket):
    """Port new valueranges from Venus to Venus on Earth"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12687

    def get_dependencies(self):
        return (PacketDependency(packet_path=PACKET_PATH_B, expected_state=PacketState.INSTALLED),
                MaxVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING))

    def fix(self, runner):
        failures = 0
        for dataitem, (before_hash, after_hash, new_code) in VALUERANGES.items():
            fix_func = lambda old_code: new_code

            if not self.migrate_python(before_hash, after_hash, self.CU_TYPE_DATAITEM, dataitem, fix_func):
                failures += 1

        if failures:
            return self.fail('Migrating the valueranges failed')

        return self.success()


class D_RemoveOldModuleFromUserMenu(ChangeDTPPacket):
    """Remove the old migration module from the user menu"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12687

    def get_dependencies(self):
        return (PacketDependency(packet_path=PACKET_PATH_C, expected_state=PacketState.INSTALLED),
                MaxVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING))

    def fix(self, runner):
        record = self.get_record(dt_num=515, key_list=['01100157', '009BWQ', 1309], di_list=['module_id'])

        if not record.delete():
            return self.fail('Could not remove module 009BWQ from work area 01100157')

        return self.success()