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

PACKET_PATH = 'migration.hotfix.S_39_5_12.wi13337_pagination.PortInterfacePagination'


STATEMENTS = {'000907': ("""SELECT MIN(POSITION) FROM
        (SELECT POSITION FROM INTERFACE_LOGGING
         WHERE
           CONFIG_ID = '{config_id}'
           AND LOGLEVEL = {log_level}
           AND POSITION > {position})""", """SELECT MIN(POSITION) FROM
        (SELECT POSITION FROM INTERFACE_LOGGING
         WHERE
           CONFIG_ID = '{config_id}'
           AND LOGLEVEL = {log_level}
           AND POSITION > {position}) subselect"""),
              '000908': ("""SELECT MAX(POSITION) FROM
        (SELECT POSITION FROM INTERFACE_LOGGING
         WHERE
           CONFIG_ID = '{config_id}'
           AND LOGLEVEL = {log_level}
           AND POSITION < {position})""", """SELECT MAX(POSITION) FROM
        (SELECT POSITION FROM INTERFACE_LOGGING
         WHERE
           CONFIG_ID = '{config_id}'
           AND LOGLEVEL = {log_level}
           AND POSITION < {position}) subselect""")}


class FixPLANTALinkPaginationMSSQL(ChangeDTPPacket):
    """Correct the step to previous/next warning/error in MSSQL in "Logging" module
 
    Therefore, corrects the SQL statements 000907 and 000908
    """
    version = 1
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13634

    def get_dependencies(self):
        return (MaxVersionDependency(version='39.5.6', version_type=VersionType.CUSTOMIZING),
                PacketDependency(packet_path=PACKET_PATH, expected_state=PacketState.INSTALLED))

    def fix(self, runner):
        for statement_id, (old_value, new_value) in STATEMENTS.items():
            record = self.get_record(dt_num=343, key_list=['-', statement_id], di_list=['source_text_clob'])

            if not self.change_value(record=record, attribute='source_text_clob',
                                     old_value=old_value, new_value=new_value):
                return self.fail('Could not change the sql statement, maybe there was a individual fix?')

        return self.success()