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


class RemoveReloaderMacro(ChangeDTPPacket):
    """Remove the python reloader macro and menu item"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 16301

    def get_dependencies(self):
        return (MinVersionDependency(version='39.4'),
                MaxVersionDependency(version='39.4'),
                PacketDependency(
                    packet_path='migration.hotfix.S_39_5_2.wi8353_python_reloader.ChangePythonReloaderMacro',
                    expected_state=PacketState.INSTALLED))

    def delete_module(self):
        record = self.get_record(405, ['009BBA'], ['id'])

        if record is not None:
            self.log('Deleting module 0099BBA')
            if not record.delete():
                return False

        else:
            self.log('Module 009BBA does not exist - nothing to delete')

        return True

    def delete_menu_item(self):
        record = self.get_record(522, ['01100537', 204], ['module_id'])

        if record is not None:
            if not self.verify_value(record=record, attribute='module_id', value='009BBA'):
                self.log('Reloader menu item does not have module 009BBA assigned?')
                return False

            self.log('Deleting menu item with python reloader')
            if not record.delete():
                return False

        else:
            self.log('Menu item for reloader macro does not exist - nothing to delete')

        return True

    def fix(self, runner):
        if not self.delete_menu_item():
            return self.fail('Could not remove reloader menu item')

        if not self.delete_module():
            return self.fail('Could not delete module 0099BBA')

        return self.success()