# -*- coding: latin-1 -*-
from ppms.migration import SQLPacket, ChangeDTPPacket, PacketCategory, PacketDependency, PacketState, MaxVersionDependency, VersionType


class B_ChangeLBvalue(ChangeDTPPacket):
    ''' Changes the value of the relationcheck LB entries '''
    wi_number = 9209
    version = 1
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_OPTIONAL

    PACKET_PATH = 'migration.hotfix.S_39_5_8.wi9209_relationcheck.A_ChangeLBdigit'
    
    def get_dependencies(self):
        return PacketDependency(packet_path=self.PACKET_PATH, expected_state=PacketState.INSTALLED)

    def fix(self, runner):
        VALUES = {686202:{'DE':{'I-Texte':'I-Texte prüfen'},'EN':{'I-texts':'I-texts check'}},
                  683993:{'DE':{'Prüfung der I-Texte':'I-Texte prüfen und korrigieren'},'EN':{'I-texts check':'Check and write I-texts'}},
                  683994:{'DE':{'Die I-Texte werden geprüft und geschrieben':'Hyperlinks prüfen'},'EN':{'The i-texts will be checked and written':'Hyperlink check'}},
                  683995:{'DE':{'I-Texte ohne Verwendung werden aus der I-Text-Tabelle gelöscht':'Hyperlinks prüfen und korrigieren'},'EN':{'Unused i-texts will be deleted from the i-text table':'Check and write hyperlinks'}},
                  683996:{'DE':{'Überprüft, ob eine I-Nummer in einer Tabelle mehrfach vorkommt':'I-Texte und Hyperlinks prüfen'},'EN':{'Checks whether an I-number appears multiple times in a table':'I-texts and hyperlink check'}}}
        
        
        for ident in sorted(VALUES):
            val = VALUES[ident]
            for lang in val:
                id_value = val[lang]
                record = self.get_record(435, [ident, lang], [1538, 1550, 1549])
                for old_value,new_value in id_value.items():
                    if not self.change_value(record, 'i_text', old_value, new_value):
                        return self.fail()
        return self.success()

class A_ChangeLBdigit(ChangeDTPPacket):
    ''' Changes the value of the relationcheck LB entries number'''
    wi_number = 9209
    version = 1
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_OPTIONAL
    
    def get_dependencies(self):
        return MaxVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING)

    def fix(self, runner):
        VALUES = {168:{0:1},
                  142:{1:2},
                  143:{3:3},
                  144:{7:4},
                  145:{17:5}}
        
        
        for ident in sorted(VALUES.keys()):
            id_value = VALUES[ident]
            for old_value,new_value in id_value.items():
                record = self.get_record(447, [ident], [41264, 41279])
                if not self.change_value(record, 'number_i2', old_value, new_value):
                    return self.fail()
        return self.success()

class D_ChangeModuleName(ChangeDTPPacket):
    ''' Changes the name of the relationcheck module'''
    wi_number = 9209
    version = 1
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_OPTIONAL
    
    PACKET_PATH = 'migration.hotfix.S_39_5_8.wi9209_relationcheck.C_ChangeCustomizing'
    
    def get_dependencies(self):
        return PacketDependency(packet_path=self.PACKET_PATH, expected_state=PacketState.INSTALLED)

    def fix(self, runner):
        OLD_VALUE = 'Relationsprüfung'
        NEW_VALUE = 'Datenbank-Konsistenz überprüfen'
        OLD_VALUE_EN = 'Relationship Check'
        NEW_VALUE_EN = 'Database-Consistency-Check'
        ident = 316760
        
        record = self.get_record(435, [ident, 'DE'], [1538, 1550, 1549])
        if not self.change_value(record, 'i_text', OLD_VALUE, NEW_VALUE):
            return self.fail()

        record = self.get_record(435, [ident, 'EN'], [1538, 1550, 1549])
        if not self.change_value(record, 'i_text', OLD_VALUE_EN, NEW_VALUE_EN):
            return self.fail()
        return self.success()
        
class C_ChangeCustomizing(SQLPacket):
    ''' Change customizing of relationcheck module '''
    wi_number = 9209
    version = 1
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_OPTIONAL

    fname = 'wi9209_setcustomizing.sql'

    PACKET_PATH = 'migration.hotfix.S_39_5_8.wi9209_relationcheck.B_ChangeLBvalue'
    
    def get_dependencies(self):
        return PacketDependency(packet_path=self.PACKET_PATH, expected_state=PacketState.INSTALLED)
    
    def fix(self, runner):
        self.apply_dml_file(self.sql_planta_de_dbms, self.fname)
        
        return self.success()

class E_CreateMacro(SQLPacket):
    ''' Create macro of relationcheck module'''
    wi_number = 9209
    version = 1
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_OPTIONAL
    
    fname = 'wi9209_createmacro.sql'
    
    PACKET_PATH = 'migration.hotfix.S_39_5_8.wi9209_relationcheck.D_ChangeModuleName'
    
    def get_dependencies(self):
        return PacketDependency(packet_path=self.PACKET_PATH, expected_state=PacketState.INSTALLED)

    def fix(self, runner):
        self.apply_dml_file(self.sql_planta_de_dbms, self.fname)
        
        return self.success()

class F_ChangeMacroOfRelationCheck(ChangeDTPPacket):
    ''' Change macro of relationcheck module. Please execute CreateMacro first. '''
    wi_number = 9209
    version = 1
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_OPTIONAL
    
    PACKET_PATH = 'migration.hotfix.S_39_5_8.wi9209_relationcheck.E_CreateMacro'
    
    def get_dependencies(self):
        return PacketDependency(packet_path=self.PACKET_PATH, expected_state=PacketState.INSTALLED)

    def fix(self, runner):
        IDENT = "009BSC"
        fixfunc = '''from ppms.database_integrity import db_consistence_test

macro_mod = ppms.get_macro_module()
target_mod = ppms.get_target_module()
target_da = target_mod.db_schema.get_records()

schema_with_error = ""

itext_consistence_test = db_consistence_test.iTextCheck()
hyperlink_consistence_test = db_consistence_test.HyperlinkCheck()
relation_consistence_test = db_consistence_test.RelationCheck()
object_protection_test = db_consistence_test.ObjectProtectionCheck()
test_successfully_completed = False

for schema in target_da:
    db_schema = schema.db_schema_id.get_raw_value()
    start_value = schema.check_cons_i_texts.get_raw_value()
    # test if schema and start value are ok
    if db_schema and start_value:
        
        # create instances and vars
        start_value = int(start_value)
        test_successfully_completed = True
        check_logfile = False
        results = []
    
        try:
            # start the test
            if start_value == 1: # itext test 
                log_file_writer = db_consistence_test.LogfileWriter(db_schema, title="iText_check")
                results.append(itext_consistence_test.start(db_schema, log_file_writer, check_and_write = False))
        
            elif start_value == 2: # itext test with writing
                log_file_writer = db_consistence_test.LogfileWriter(db_schema, title="iText_fix")
                results.append(itext_consistence_test.start(db_schema, log_file_writer, check_and_write = True))
            
            elif start_value == 3: # hyperlink test
                log_file_writer = db_consistence_test.LogfileWriter(db_schema, title="Hyperlink_check")
                results.append(hyperlink_consistence_test.start(db_schema, log_file_writer, check_and_write = False))
            
            elif start_value == 4: # hyperlink test with writing
                log_file_writer = db_consistence_test.LogfileWriter(db_schema, title="Hyperlink_fix")
                results.append(hyperlink_consistence_test.start(db_schema, log_file_writer, check_and_write = True))
            
            elif start_value == 5: # itext and hyperlink test
                log_file_writer = db_consistence_test.LogfileWriter(db_schema, title="iText_and_Hyperlink_check")
                results.append(itext_consistence_test.start(db_schema, log_file_writer, check_and_write = False))
                results.append(hyperlink_consistence_test.start(db_schema, log_file_writer, check_and_write = False))
            
            elif start_value == 6: # itext and hyperlink test with writing
                log_file_writer = db_consistence_test.LogfileWriter(db_schema, title="iText_and_Hyperlink_fix")
                results.append(itext_consistence_test.start(db_schema, log_file_writer, check_and_write = True))
                results.append(hyperlink_consistence_test.start(db_schema, log_file_writer, check_and_write = True))
            
            elif start_value == 7: # relation check
                log_file_writer = db_consistence_test.LogfileWriter(db_schema, title="Relations_check")
                results.append(relation_consistence_test.start(db_schema, log_file_writer, write_sql = True))
                           
            elif start_value == 8: # object check
                log_file_writer = db_consistence_test.LogfileWriter(db_schema, title="Object_protection_check")
                results.append(object_protection_test.start(db_schema, log_file_writer, write_sql = True))
                
            elif start_value == 9: # check all
                log_file_writer = db_consistence_test.LogfileWriter(db_schema, title="iText_Hyperlink_Relation_and_Object_check")
                results.append(itext_consistence_test.start(db_schema, log_file_writer, check_and_write = False))
                results.append(hyperlink_consistence_test.start(db_schema, log_file_writer, check_and_write = False))
                results.append(relation_consistence_test.start(db_schema, log_file_writer, write_sql = True))
                results.append(object_protection_test.start(db_schema, log_file_writer, write_sql = True))
            
        except Exception as e:
            test_successfully_completed = False
            schema_with_error += db_schema + ", "
            raise e
        
        finally:
            # write to log
            for result in results:
                for header, data in result.items():
                    log_file_writer.get_data(header, data)
                    if len(data) > 0:
                        check_logfile = True
            log_file_writer.close()
        
if test_successfully_completed:
    if check_logfile:
        ppms.ui_message_box("Consistence test",  "Successfully completed - Some Checks failed. Please check logfile in working directory.")
    else:
        ppms.ui_message_box("Consistence test",  "Successfully completed - All Checks performed, no errors found.")
else:
    ppms.ui_message_box("Consistence test",  "Not successfully completed - Error in schema {0} Please repeat the test or contact your administrator".format(schema_with_error))'''
        

        record = self.get_record(405, ['009BSC'], [40819])

        if self.change_value(record, 'py_macro_text', 'from ppms.database_integrity', fixfunc):
            return self.success()
        return self.fail()
        
        
        
        