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


class ChangeDIsToVirtAndAddVR(SQLPacket):
    """Replace DIs 008708 'calc_end' and 008766 'req_end' with a Python VR

    The sources for these data items are no longer written into project data by
    scheduling, hence reports must calculate them as well."""

    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 20948

    filename = 'WI20948_change_sql_query.sql'
    sql_script = """update dt412
                    set DI027352='def computeOutput(di):
    rec = di.get_dtp_record()
    calc_end = rec.calc_end.get_value()
    requested_end = rec.req_end.get_value()
    if not calc_end or not requested_end:
        return 0
    return calc_end - requested_end

computeOutput.deps = ("calc_end","req_end")',
                    DI001990='PY',
                    DI000275=1,
                    DI000241=0,
                    DI028175=0,
                    DI000215='',
                    DI040837 = ''
                    where DI000238 in ('008708','008766')"""

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

    def fix(self, packet_runner):

        self.apply_dml_file(self.sql_planta_de_dbms, self.filename)
        try:
            self.modify_and_log("alter table dt823 drop column di008708")
            self.modify_and_log("alter table dt824 drop column di008766")
        except ppms.DatabaseError:
            self.log("Error: Drop Column failed")

        self.modify_and_log(self.sql_script)


        return self.success()
