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


class UpdatePythonIDOfDIsInDT153(SQLPacket):
    '''updates python_ids (DI041035) of DT153. Only needed in rare cases that a customer system didn't have a custom scheme yet, but will need one after a db update.'''
    wi_number = 21192  # The workitem number this packet belongs to. Only relevant for packets by PLANTA
    version = 0
    done_after_success = True  # Sets the "Erledigt" flag after running successfully
    run_on_startup = False  # Runs this migration packet when the server is started in migration mode
    category = PacketCategory.CATEGORY_MANDATORY  # Categorizes the packet

    current_ids = []
    wished_ids = [['008263', 'di'], ['008262', 'license'], ['008271', 'own_lic'], ['008272', 'osk'], ['008273', 'owner'], ['008274', 'group'], ['008275', 'any'], ['008276', 'counter_value_1'], ['008277', 'counter_value_2']]

    def fix(self,runner):
        self.get_current_pythonIDs()
        try:
            self.update_pythonIDs(self.wished_ids)
        except Exception as error:
            self.revert_in_case_something_went_wrong()
            self.log(error)
            return self.fail(error)
        return self.success()


    def get_current_pythonIDs(self):
        query = """select DI000238,DI041035 from DT412 where DI000239 = 153"""
        self.current_ids = ppms.db_select(query)

    def update_pythonIDs(self,wished_changes):
        query_template = """update DT412 set DI041035 = '{python_id}' where DI000238 = '{di_to_change}'"""
        for change in wished_changes:
            query = query_template.format(python_id = change[1], di_to_change = change[0])
            self.modify_and_log(query)

    def revert_in_case_something_went_wrong(self):
        self.update_pythonIDs(self.current_ids)

