# -*- coding: utf-8 -*-
from ppms.migration.packet import *
from . import DEFAULT_CUSTOMIZING_DEPENDENCY

CONFIG_PARAMETER_VR = """from ppms import ppms
from ppms.interface import get_module_subclass, BaseInterfaceModule

# Use a processInput so we can write to the statusbar
def processInput(di, oldValue):
    dtp_record = di.get_dtp_record()

    parameter = dtp_record.name.get_value()
    value = di.get_value()

    module = dtp_record.source.get_value()
    subclass = get_module_subclass(module)

    if subclass and issubclass(subclass, BaseInterfaceModule):
        if subclass.is_valid_parameter_value(parameter=parameter, value=value):
            return value

    return oldValue


processInput.deps = ('DI062668', 'DI062667')"""

MAPPING_PARAMETER_VR = """from ppms import ppms
from ppms.interface import get_mapping_instance_from_uuid

# Use a processInput so we can write to the statusbar
def processInput(di, oldValue):
    dtp_record = di.get_dtp_record()

    mapping_id = dtp_record.mapping_id.get_value()
    parameter = dtp_record.name.get_value()
    value = di.get_value()

    mapping = get_mapping_instance_from_uuid(uuid=mapping_id)
    if mapping and mapping.is_valid_parameter_value(parameter=parameter, value=value):
        return value

    return oldValue

processInput.deps = ('DI062765', 'DI062753')"""


class PortNewInterfaceParameterHandling(SQLPacket, ChangeDTPPacket):
    '''Port the new parameter handling in the interface'''
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12060

    fname = 'wi12060_parameters.sql'

    def get_dependencies(self):
        return DEFAULT_CUSTOMIZING_DEPENDENCY

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

        record = self.get_record(412, ['062669'], [1990, 27352])
        if not self.change_value(record, 'valuerange', '', CONFIG_PARAMETER_VR):
            return self.fail()

        if not self.change_value(record, 'wb_type', '', 'PY'):
            return self.fail()

        record = self.get_record(412, ['062752'], [1990, 27352])
        if not self.change_value(record, 'valuerange', '', MAPPING_PARAMETER_VR):
            return self.fail()

        if not self.change_value(record, 'wb_type', '', 'PY'):
            return self.fail()

        return self.success()
