from ppms.migration import SQLPacket, ChangeDTPPacket, PacketCategory, MaxVersionDependency
from ppms import ppms


class VirtualizeOverlappingDIs(SQLPacket, ChangeDTPPacket):
    """Virtualizes the DIs (009351, 009352, 009353) for the overlapping bar in schedule modules"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 21768

    dis_with_value_range = [('009351', '''from ppms.tasks import di009351_sd_overlapping_computeSqlValueRange

# def computeSqlValueRange(dt_name)

computeSqlValueRange = di009351_sd_overlapping_computeSqlValueRange
'''), ('009352', '''from ppms.tasks import di009352_ed_overlapping_computeSqlValueRange

# def computeSqlValueRange(dt_name)

computeSqlValueRange = di009352_ed_overlapping_computeSqlValueRange
'''), ('009353', '''from ppms.tasks import di009353_days_overlapping_computeOutput

computeOutput = di009353_days_overlapping_computeOutput''')]
    filename = 'WI21768_virtualize_overlapping_dis.sql'
    deletion_file = 'WI21768_virtualize_overlapping_dis_delete.sql'

    def delete_old_data(self):
        self.log_heading('Wiping data that could cause conflicts')
        self.apply_dml_file(self.sql_planta_de_ansi, self.deletion_file)

    def insert_new_sql_querys(self):
        self.log_heading('Inserting new data')
        self.apply_dml_file(self.sql_planta_de_dbms, self.filename)

    def fix(self, packet_runner):
        for di, value_range in self.dis_with_value_range:
            column_name = 'DI' + di

            if self.column_exists(table_name='DT463', column_name=column_name):
                self.drop_column('DT463', column_name, remove_customizing=False)
                rec = ppms.search_record(412, [di], ['valuerange', 'virtual', 'termin_scheduling', 'wb_type', 'column_name',
                                                     'db_position'])
                self.change_value(rec, 'valuerange', None, value_range)
                self.change_value(rec, 'virtual', None, 1)
                self.change_value(rec, 'termin_scheduling', None, 0)
                self.change_value(rec, 'wb_type', None, 'PY')
                self.change_value(rec, 'column_name', None, '')
                self.change_value(rec, 'db_position', None, 0)
            else:
                self.log('Column {} was already dropped'.format(column_name))

        self.delete_old_data()
        self.insert_new_sql_querys()

        return self.success()
