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


class SapPSPImprovements(SQLPacket, ChangeDTPPacket):
    """Schema changes for the SAP psp element functionality"""
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 21144

    sql_script = 'WI21144_sap_psp_improvements.sql'

    def get_dependencies(self):
        return MaxVersionDependency(version='39.5.10'),

    def virtualize_psp_table(self):
        for table in ['DT963', 'DT974']:
            for column in ['EFFORT_PLAN', 'EFFORT_ACT', 'EFFORT_REM', 'COSTS_PLAN', 'COSTS_ACT', 'COSTS_REM',
                           'EFFORT_PLAN_PLANTA', 'EFFORT_ACT_PLANTA', 'EFFORT_REM_PLANTA',
                           'COSTS_REM_PLANTA', 'COSTS_ACT_PLANTA', 'COSTS_PLAN_PLANTA', 'BUDGET']:
                if self.column_exists(table_name=table, column_name=column):
                    self.drop_column(table_name=table, column_name=column, remove_customizing=False)

    def fix(self, runner):
        self.virtualize_psp_table()

        self.apply_dml_file(self.sql_planta_de_dbms, self.sql_script)

        self.rename_table_ported(old_table_name='SAP_PSP_AAE', new_table_name='DT975')
        self.rename_table_ported(old_table_name='SAP_PSP_AAE_REPORT', new_table_name='DT976')

        # Kinda unnecessary, since the DB import will take care of this
        record = self.get_record(415, ['975'], ['variable_name'])
        self.change_value(record=record, attribute='variable_name', old_value='SAP_PSP_AAE', new_value='DT975')

        record = self.get_record(415, ['976'], ['variable_name'])
        self.change_value(record=record, attribute='variable_name', old_value='SAP_PSP_AAE_REPORT', new_value='DT976')

        return self.success()

    # Ported from a newer server version
    def rename_table_ported(self, old_table_name, new_table_name):
        """Renames a table

        returns True/False
        """
        if not self.object_is_table(object_name=old_table_name):
            self.log('No table with name "{}" exists'.format(old_table_name))
            return False

        if self.object_is_table(object_name=new_table_name):
            self.log('A table with the name "{}" already exists'.format(new_table_name))
            return False

        dbms = ppms.db_get_dbms_name()
        if dbms == DBMS_ORACLE:
            stmt = """ALTER TABLE {old_table_name} RENAME TO {new_table_name}"""
            self.modify_and_log(stmt.format(old_table_name=old_table_name, new_table_name=new_table_name),
                                log_rows=False)
        elif dbms == DBMS_MSSQL:
            stmt = """sp_rename '{old_table_name}', '{new_table_name}'"""
            self.modify_and_log(stmt.format(old_table_name=old_table_name, new_table_name=new_table_name),
                                log_rows=False)
        else:
            raise NotImplementedError(dbms)

        return True
