# -*- coding: utf-8 -*-
import itertools

from ppms import ppms
from ppms import interface
from ppms.migration.packet import *
from . import DEFAULT_CUSTOMIZING_DEPENDENCY


class ConvertOldEnricherToNewConverter(BasePacket):
    """Convert the old GetPersonId enricher to the new ConvertResourceIdToPersonId"""
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12520

    def get_dependencies(self):
        return DEFAULT_CUSTOMIZING_DEPENDENCY

    def fix(self, runner):
        query = """SELECT UUID FROM INTERFACE_MAPPING WHERE OBJECT = 'GetPersonId'"""
        result = ppms.db_select(query)

        for uuid in itertools.chain(*result):
            self.log('Changing the GetPersonId enricher for mapping "%s"' % uuid)
            mapping_record = ppms.search_record(562, [uuid], ['object', 'type'])
            mapping_record.type.set_value(interface.MappingType.CONVERTER)
            mapping_record.object.set_value('ConvertResourceIdToPersonId')
            save_result = mapping_record.save(('type', 'object'))

            if save_result:
                self.log('The enricher was changed into a converter successfully')
            else:
                self.fail('Failed to change a GetPersonId enricher to a ConvertResourceIdToPersonId converter')

        return self.success()


class ConvertEqualsValidatorToCompareTo(BasePacket):
    """Convert all "Equals" validator mappings to "ComparesTo" validators"""
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12520

    def get_dependencies(self):
        return DEFAULT_CUSTOMIZING_DEPENDENCY

    def fix(self, runner):
        query = """SELECT UUID FROM INTERFACE_MAPPING WHERE OBJECT = 'Equals'"""
        result = ppms.db_select(query)

        for uuid in itertools.chain(*result):
            self.log('Changing the Equals validator for mapping "%s"' % uuid)
            mapping_record = ppms.search_record(562, [uuid], ['object'])
            mapping_record.object.set_value('ComparesTo')
            save_result = mapping_record.save(('object',))

            if save_result:
                self.log('The "Equals" validator was changed into a "ComparesTo" successfully')
            else:
                self.fail('Failed to change a "Equals" validator to a "ComparesTo" converter')

        return self.success()