# -*- coding: utf-8 -*-

from ppms.migration.packet import BasePacket
from ppms.database_integrity import db_consistence_test

class __StartRelationTest__(BasePacket):
    version = 1
    done_after_success = False
    run_on_startup = False

    def fix(self, runner):
        # get active DB schemas
        active_schemas = db_consistence_test.ConsistencyTest.get_db_schemas(only_schemas_which_are_in_zaehlerstand_mapping=True)

        # start tests with specific schema
        for db_schema in active_schemas:
            # create instances
            test_result = list()
            itext_consistence_check = db_consistence_test.iTextCheck()
            hyperlink_consistence_check = db_consistence_test.HyperlinkCheck()
            # start
            test_result.append(itext_consistence_check.start(test_specific_schema = db_schema))
            test_result.append(hyperlink_consistence_check.start(test_specific_schema = db_schema))

        # start tests without specific schema
        di_and_dt_existence_check = db_consistence_test.DataitemAndDatatableCheck()
        test_result.append(di_and_dt_existence_check.start())

        # write to log
        for result in test_result:
            for header, data in result.items():
                self.write_result_to_migration_log(header, data)


    def write_result_to_migration_log(self, header, data_dict):
        """write data to migration log (ppms.migration.packet.BasePacket -Log)
            nearly the same function is in db_consistence_test.py (LogfileWriter.get_data()) """
        # this function writes data into the logfile
        # needs a header and a data dict which includes data to write
        self.log('\n' + header + '\n')

        # no data under this topic
        if len(data_dict.keys()) == 0:
            self.log(' --- None ---')
            self.log('\n')

        # keys are headings and the values are the text
        for key in data_dict.keys():
            self.log(str(key) + ' ('+str(len(data_dict[key]))+') '+'\n')

            line_count = 0;
            value_text = ''
            for value in data_dict[key]:
                if line_count >= 10: # line break after 10 records
                    value_text = value_text + ('\n')
                    line_count = 0
                if value.__class__ is float:
                    value = int(value)

                value_text = value_text + str(value) + ", "
                line_count +=1

            self.log(value_text+'\n')