# -*- coding: utf-8 -*-
from ppms import ppms
from ppms.migration import SQLPacket, PacketCategory


CODE = """def executeProcessAction(mts_rec=None,object_id=None):
        from ppms.processrules import transfer_phase

        transfer_phase(object_id, mts_rec)

        return True

ppms.get_planta_session_dict()["planta_functions"]=[executeProcessAction]
"""


class AddTransferProcessAction(SQLPacket):
    """Port the transfer process action"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13734

    def fix(self, runner):
        QUERY = """SELECT COUNT(1) FROM DT489 WHERE DI041228 = 'Aktion Übergabe'"""

        count = int(ppms.db_select(QUERY)[0][0])
        if count > 0:
            self.log('Process action already exists!')
            return self.success()

        attributes = {'name': 'Aktion Übergabe',
                      'rule_type': 250,
                      'class_id': 195,
                      'object_type': 192,
                      'sql_rule': CODE}

        record = ppms.create_record(489, attributes)
        if not record:
            return self.fail('Record could not be created with the attributes: %s' % attributes)

        if not record.save():
            return self.fail('Record could not be saved with the attributes: %s' % attributes)

        self.log('The process action "Übergabe" was successfully created')

        return self.success()
