# -*- coding: utf-8 -*-
from ppms import ppms
from ppms.migration import ChangeDTPPacket, SQLPacket, PacketCategory, MinVersionDependency, MaxVersionDependency, VersionType

DATAITEM_DICT = {
                    ('026938',): {'df_length': [5, 10]},
                    ('000504',): {'df_length': [6, 10]},
                    ('027984',): {'db_length': [8, 4]},
                    ('006119',): {'df_length': [6, 10]}
                }

DELETE_AUTONR = [('000','040825'),('011','040825'),('100','040825')]
        
class AutomaticNumberLongerThanDbLengthOfDataField(SQLPacket, ChangeDTPPacket):
    '''Change customizing of automatic numbers and DIs with automatic numbers
 
    Change following DB/DF lengths:
    - DT506.DI026938: df_length [5 -> 10]
    - DT414.DI000504: df_length [6 -> 10]
    - DT404.DI027984: db_length [8 -> 4]
    - DT909.DI006119: df_length [6 -> 10]
 
    Delete all automatic numbers for DT823.DI040825
 
    Correct "Zaehlerstand 1", "Zaehlerstand von" and "Zaehlerstand bis" for DT818.DI007935 if they're incorrect
    '''
    
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13301
    
    def get_dependencies(self):
        return (MinVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),
                MaxVersionDependency(version='39.5.5', version_type=VersionType.CUSTOMIZING))
    
    def remove_dtp_record(self, datatable, primary_key):
        autonumber_record = self.get_record(datatable, list(primary_key), ['uuid'])
        if not autonumber_record: return True
        return autonumber_record.delete()
    
    def change_record(self, datatable, primary_key, change_dictionary):
        old_value = 0
        new_value = 1
        record = self.get_record(datatable, list(primary_key), list(change_dictionary.keys()))
        for field in change_dictionary.keys():
            old_new_values = change_dictionary.get(field)
            self.change_value(record, field, old_new_values[old_value], old_new_values[new_value])
            
    def fix(self, runner):
        self.log("Fix customizing of dataitems")
        for dataitem in DATAITEM_DICT.keys():
            self.change_record(412, dataitem, DATAITEM_DICT.get(dataitem))
            
        autonr_dataitems = {
                            "007935": {"current_length": 9, "change_length_to": 8}
                           }
        licenses_to_check = ("000", "011", ppms.uvar_get("@3"))
        for dataitem in autonr_dataitems.keys():
            for license in licenses_to_check:
                autonr_record = self.get_record(439, [license, dataitem], ["vr_counter_1from", "vr_counter_1_to", "counter_value_1"])
                if not autonr_record:
                    continue
                counter_from = autonr_record.vr_counter_1from
                counter_to = autonr_record.vr_counter_1_to
                counter_value_1 = autonr_record.counter_value_1
                fields = autonr_dataitems.get(dataitem)
                for dtp_record in (counter_from, counter_to, counter_value_1):
                    if len(dtp_record.get_value()) == fields.get("change_length_to"):
                        self.log("Record has already the right state.")
                        continue
                    elif len(dtp_record.get_value()) == fields.get("current_length"):
                        dtp_record.set_value(dtp_record.get_value()[:fields.get("change_length_to")])
                        if not dtp_record.get_dtp_record().save():
                            self.log("Could not save the record")
                        else:
                            self.log("SUCCESS: Saved")
                    else:
                        self.log("Record has neither the expected nor the right state.")
                        continue                
        
        for autonr_rec in DELETE_AUTONR:
            self.log("Removing autonumber for license %s / DI%s"%autonr_rec)
            self.remove_dtp_record(439, autonr_rec)
            
        return self.success()