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


class BaseProcessActionCode(BasePacket):
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13732

    PROCESS_ACTION_CODE = None

    def port_process_action(self, name):
        QUERY = """SELECT COUNT(1) FROM DT489 WHERE DI041228 = '{}'""".format(name)

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

        attributes = {'name': name,
                      'rule_type': 250,
                      'class_id': 195,
                      'object_type': 192,
                      'sql_rule': self.PROCESS_ACTION_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 "{}" was successfully created'.format(name))

        return self.success()


class AddCheckByBoardCode(BaseProcessActionCode):
    """Add the "Prüfung für Abgabe" process action to the system"""

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

    hand_in_for_approval(object_id, mts_rec)

    return True

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

    def fix(self, runner):
        return self.port_process_action(name='Prüfung für Abgabe')


class AddHandInToBoardCode(BaseProcessActionCode):
    """Add the "Abgabe an Gremium" process action to the system"""

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

    hand_in(object_id, mts_rec, requires_valid_approval_resource=False)

    return True

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

    def fix(self, runner):
        return self.port_process_action(name='Abgabe an Gremium')

