# -*- coding: utf-8 -*-
from ppms.migration import ChangeDTPPacket, PacketCategory, MinVersionDependency, MaxVersionDependency

OLD_VALUE = """def processInput(di, oldvalue):
    rec = di.get_dtp_record()
    cur_value = di.get_value()
    dt_id = rec.dt_id.get_value()
    sql_check = ppms.db_select(ppms.get_query("000218").format("uuid",dt_id))[0][0]
    if sql_check == 0:
        if cur_value != oldvalue:
            ppms.ui_message_id("1038")
            return oldvalue
    else:
        return cur_value"""

NEW_VALUE = """def processInput(di, oldvalue):
    rec = di.get_dtp_record()
    cur_value = di.get_value()
    dt_id = rec.dt_id.get_value()
    sql_check = len(ppms.db_select("Select * from dt412 where di000215='UUID' and di000239 = '" + str(dt_id) +"'"))
    if sql_check == 0:
        if cur_value != oldvalue:
            ppms.ui_message_id("1038")
            return oldvalue
    else:
        return cur_value
"""


class FixDT516ValueRange(ChangeDTPPacket):
    """
    Correct the valuerange of DI063234
    """
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12638

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

    def fix(self, runner):
        record = self.get_record(dt_num=412, key_list=['063234'], di_list=['valuerange'])

        if not self.change_value(record=record, attribute='valuerange', old_value=OLD_VALUE, new_value=NEW_VALUE):
            return self.fail('Could not change the valuerange, maybe there was a individual customizing')

        return self.success()