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


class FetchSizeMessages(SQLPacket):
    '''Change dialog messages for fetch size limit handling: They now have some parameters'''
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12982

    UPDATE_ASK_CANCEL = """UPDATE DT435 SET DI001549 = 'Das Filterergebnis ist mit %d Datensätzen sehr gross und kann zu langen Ladezeiten führen.
Fortfahren?' WHERE di001538 = 799172 AND di001550 = 'DE'"""
    UPDATE_FORCE_CANCEL = """UPDATE DT435 SET DI001549 = 'Das Filterergebnis im Modul %s hat mit %d gefundenen Datensätzen das eingestellte Limit (%d) überschritten.
Filtern abgebrochen.
Ändern Sie Ihren Filter, oder wenden Sie sich an Ihren Customizer.' WHERE di001538 = 799173 AND di001550 = 'DE'"""

    def get_dependencies(self):
        return (MaxVersionDependency('39.5.6'),)

    def translation_exists(self, translation_number, language):
        record = ppms.search_record(435, [translation_number, language], ['i_no_id'])

        return record is not None

    def translations_exist(self):
        return self.translation_exists(translation_number=799172, language='DE') and \
               self.translation_exists(translation_number=799173, language='DE')

    def fix(self, runner):
        if not self.translations_exist():
            self.log('Please check if the packet FetchSizeLimits from server 9 was executed correctly')
            return self.fail('The translations that should be updated do not exist in this system')

        fails = 0

        if not self.modify_and_log(self.UPDATE_ASK_CANCEL):
            fails += 1
        if not self.modify_and_log(self.UPDATE_FORCE_CANCEL):
            fails += 1

        if fails:
            return self.fail()

        return self.success()