from ppms.migration import SQLPacket, PacketCategory, MinVersionDependency, MaxVersionDependency, VersionType
from ppms.constants import DBMS_MSSQL


class PortBugfixForWorkReportingModuleToVoe(SQLPacket):
    """
    fixes an sql-error when trying to report working-hours

    neccessary in venus on earth (39.4.X) for mssql
    """

    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 14572

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

    def fix(self, runner):
        if not self.DBMS == DBMS_MSSQL:
            self.log("Only required for MSSQL systems.")
            return self.success()

        drop_trigger = r'''
        IF  EXISTS (SELECT 1 FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[T_CREATE_DT472]'))
        DROP TRIGGER [dbo].[T_CREATE_DT472]
        '''
        fname = 'wi14572_port_workreporting_bugfix_to_voe.sql'

        self.modify_and_log(query=drop_trigger, log_rows=True)
        self.apply_fix_ddl_file(sql_dialect=self.sql_planta_de_dbms, filename=fname, split=False)
        self.success()