# -*- coding: utf-8 -*-
from ppms.migration import SQLPacket, PacketCategory, MaxVersionDependency, VersionType
from ppms.constants import DBMS_ORACLE, DBMS_MSSQL
from ppms import ppms


class MoveDeviationOutOfScheduling(SQLPacket):
    """This recreates the deviation logic of DI001296+DI001177, which were former calculated by scheduling,
    as a value range and changes the DI to be virtual."""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 20311
    
    sql_script = """update dt412
set DI027352='def computeOutput(di):
    rec = di.get_dtp_record()
    calc_end = rec.calc_end.get_value()
    requested_end = rec.requested_end.get_value()
    if not calc_end or not requested_end:
        return 0
    return calc_end - requested_end

computeOutput.deps = ("calc_end","requested_end")',
DI001990='PY',
DI000275=1,
DI000241=0,
DI028175=0,
DI000215=''
where DI000238 in ('001296','001177')"""
    
    def get_dependencies(self):
        return MaxVersionDependency(version='39.5.9', version_type=VersionType.CUSTOMIZING),
    
    def fix(self, packet_runner):
    
        self.modify_and_log(self.sql_script)
        
        try:
            if self.DBMS == DBMS_MSSQL:
                self.modify_and_log("alter table dt461 drop constraint DT461DI001296_DEFAULT")
            
            self.modify_and_log("alter table dt461 drop column DI001296")
            self.modify_and_log("alter table dt463 drop column DI001177")
        except ppms.DatabaseError:
            # as this is a VoE and Venus package, the objects might be already there
            pass
        
        return self.success()
