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

        
class ChangeCategoryLength(SQLPacket,ChangeDTPPacket):
    """Changes the length of DI007711 "Kategorie" in DT810 "Risiken" and DI029571 in DT812 "Chancen" to 50 
       to avoid the problem of cutted text in these fields"""
    wi_number = 11797
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY

    def get_dependencies(self):
        return (MinVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),
                MaxVersionDependency(version='39.5.5', version_type=VersionType.CUSTOMIZING))

    def fix(self, runner):
        VALUES = {'007711':{10:50},
                  '029571':{10:50}}
        
        for di in sorted(VALUES.keys()):
            id_value = VALUES[di]
            for old_value,new_value in id_value.items():
                record = self.get_record(412, [di], [254, 246])
                if not self.change_value(record, 'df_length', old_value, new_value):
                    return self.fail()
                if not self.change_value(record, 'db_length', old_value, new_value):
                    return self.fail()
                    
    
        if self.DBMS == DBMS_ORACLE:
            queries = ['ALTER TABLE DT810 MODIFY DI007711 varchar2(50 CHAR)',
                       'ALTER TABLE DT812 MODIFY DI029571 varchar2(50 CHAR)']
        elif self.DBMS == DBMS_MSSQL:
            queries = ['ALTER TABLE DT810 ALTER COLUMN DI007711 varchar(50)',
                       'ALTER TABLE DT812 ALTER COLUMN DI029571 varchar(50)']
        else:
            return self.fail('No statement for this DBMS')
            
        for query in queries:
            self.modify_and_log(query)

        return self.success()