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

from ppms.migration import BasePacket, PacketCategory
from ppms.database_integrity import db_consistence_test


# TODO: Fetch dynamically?
SCHEMAS = ['Q1B', 'Q2B', 'Q3B', 'Q4B', 'Q5B', 'Q6B']


class ConsistencyCheckWorkArounder(io.StringIO):
    """Workaround for the consistency check closing files"""
    def __enter__(self):
        self.original_close = self.close
        self.close = lambda: True

        return self

    def __exit__(self, *args):
        self.original_close()


class ItextCheckPacket(BasePacket):
    """Run the itext correction of the database consistency check"""
    done_after_success = False
    run_on_startup = False
    category = PacketCategory.CATEGORY_HELPER
    wi_number = 16905

    def fix(self, packet_runner):
        itext_consistence_test = db_consistence_test.iTextCheck()

        got_negative_results = False

        for schema in SCHEMAS:
            with ConsistencyCheckWorkArounder() as dummy_log:
                results = itext_consistence_test.start(schema, file=dummy_log, check_and_write=True)
                if results:
                    for result in results.values():
                        if result:
                            got_negative_results = True

                    self.log("{schema}: {results}".format(**locals()))

        if got_negative_results:
            return self.fail()

        return self.success()
        
class HyperlinkCheckPacket(BasePacket):
    """Run the hyperlink correction of the database consistency check"""
    done_after_success = False
    run_on_startup = False
    category = PacketCategory.CATEGORY_HELPER
    wi_number = 16905

    def fix(self, packet_runner):
        hyperlink_consistence_test = db_consistence_test.HyperlinkCheck()

        got_negative_results = False

        for schema in SCHEMAS:
            with ConsistencyCheckWorkArounder() as dummy_log:
                results = hyperlink_consistence_test.start(schema, file=dummy_log, check_and_write=True)
                if results:
                    for result in results.values():
                        if result:
                            got_negative_results = True

                    self.log("{schema}: {results}".format(**locals()))

        if got_negative_results:
            return self.fail()

        return self.success()


class PlaceholderCheckPacket(BasePacket):
    """Run the placeholder correction of the database consistency checks

    This check searches for '-' and sets them to null as well as deleting dummy data records which have '-' as primary
    key value."""
    done_after_success = False
    run_on_startup = True
    category = PacketCategory.CATEGORY_HELPER
    wi_number = 17899

    def fix(self, packet_runner):
        placeholder_consistency_test = db_consistence_test.PlaceholderValuesCheck()

        for schema in SCHEMAS:
            with ConsistencyCheckWorkArounder() as dummy_log:
                results = placeholder_consistency_test.start(schema, dummy_log, check_and_write=True, write_sql=False)
                if results:
                    self.log("{schema}: {results}".format(**locals()))

        return self.success()