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

PACKET_PATH = 'migration.hotfix.S_39_5_4.wi11533_port_universal_interface_VoE.PortCustomizingUniversalInterface'


class PortNewLoggingDataArea(SQLPacket, ChangeDTPPacket):
    """Port a DataArea for the PLANTA Link logging module"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13272

    FILENAME = 'wi13272_interface_logging.sql'

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

    def fix(self, runner):
        record = self.get_record(dt_num=406, key_list=[344213], di_list=['id'])
        self.log('Trying to delete old da assignment')
        if not record.delete():
            return self.fail('Could not delete it')

        self.log('Inserting new DA')
        self.apply_dml_file(self.sql_planta_de_dbms, self.FILENAME)

        return self.success()


class ChangePLANTALinkLoggingModule(ChangeDTPPacket):
    """Make changes to the PLANTA Link logging module"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13272

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

    def fix(self, runner):
        failures = 0

        record = self.get_record(dt_num=405, key_list=['009C3L'], di_list=['mod_class'])
        if not self.change_value(record=record, attribute='mod_class', old_value=12, new_value=4):
            failures += 1

        record = self.get_record(dt_num=406, key_list=[344170], di_list=['parent_pos', 'display_behavior'])
        if not self.change_value(record=record, attribute='parent_pos', old_value=0, new_value=1):
            failures += 1

        if not self.change_value(record=record, attribute='display_behavior', old_value=1, new_value=2):
            failures += 1

        if failures:
            return self.fail()

        return self.success()