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

STATEMENTS = {DBMS_ORACLE: ["ALTER TABLE INTERFACE_CONFIG ADD THRESHOLD_PERCENT NUMBER",
                            "ALTER TABLE INTERFACE_CONFIG MODIFY (\"THRESHOLD_PERCENT\" DEFAULT 0)",
                            "UPDATE INTERFACE_CONFIG SET THRESHOLD_PERCENT = DEFAULT",
                            "ALTER TABLE INTERFACE_CONFIG ADD THRESHOLD_SECONDS NUMBER(5,0)",
                            "ALTER TABLE INTERFACE_CONFIG MODIFY (\"THRESHOLD_SECONDS\" DEFAULT 0)",
                            "UPDATE INTERFACE_CONFIG SET THRESHOLD_SECONDS = DEFAULT"],
              DBMS_MSSQL: ["ALTER TABLE INTERFACE_CONFIG ADD THRESHOLD_PERCENT FLOAT",
                           "ALTER TABLE INTERFACE_CONFIG ADD constraint DT560DI064051_DEFAULT DEFAULT 0 FOR ["
                           "THRESHOLD_PERCENT]",
                           "UPDATE INTERFACE_CONFIG SET THRESHOLD_PERCENT = DEFAULT",
                           "ALTER TABLE INTERFACE_CONFIG ADD THRESHOLD_SECONDS NUMERIC(5,0)",
                           "ALTER TABLE INTERFACE_CONFIG ADD constraint DT560DI064050_DEFAULT DEFAULT 0 FOR ["
                           "THRESHOLD_SECONDS]",
                           "UPDATE INTERFACE_CONFIG SET THRESHOLD_SECONDS = DEFAULT"]}


class AddCancelThresholdColumns(SQLPacket):
    """Add the cancel threshold columns"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 17232

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

    def fix(self, packet_runner):
        if self.column_exists(table_name='INTERFACE_CONFIG', column_name='THRESHOLD_PERCENT') or \
                self.column_exists(table_name='INTERFACE_CONFIG', column_name='THRESHOLD_SECONDS'):
            self.log('Columns already exist in the system!')
            return self.success()

        for statement in STATEMENTS[self.DBMS]:
            self.modify_and_log(statement, log_rows=False)

        return self.success()
