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


class DeleteNullRecord(SQLPacket):
    """Delete an obsolete record that blocks the constraint activation"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 18950

    def get_dependencies(self):
        return (MinVersionDependency(version='39.5.7'),
                MaxVersionDependency(version='39.5.7'))

    def delete_record(self):
        query = """DELETE
                     DT423
                   WHERE
                     NOT EXISTS (SELECT
                                   1
                                 FROM
                                   DT422
                                 WHERE
                                   DI000347 = DI000370)
                     AND DI000370 IS NOT NULL"""
        return self.modify_and_log(query)

    def fix(self, packet_runner):
        record_deleted = self.delete_record()

        if record_deleted:
            self.log('Record was successfully deleted')
        else:
            self.log('Record must have already been deleted')

        return self.success()
