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

PACKET_PATH = 'migration.customizing.DB_39_5_7.WI14635_AddMissingColumnsInMP.A_AddMissingColumnsInMP'


class A_AddMissingColumnsInMP(SQLPacket):
    "Adding a Missing Column in MITARBEITER_POOL"

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

    STATEMENTS = {DBMS_ORACLE: ("ALTER TABLE MITARBEITER_POOL ADD USER_MV_CREATION NUMBER(5,0) DEFAULT 0",
                                "ALTER TABLE MITARBEITER_POOL ADD PARALLEL_SESSIONS NUMBER(5,0) DEFAULT 0"),
                  DBMS_MSSQL: ("ALTER TABLE MITARBEITER_POOL ADD USER_MV_CREATION NUMERIC(5,0) DEFAULT 0",
                               "ALTER TABLE MITARBEITER_POOL ADD PARALLEL_SESSIONS NUMERIC(5,0) DEFAULT 0")}

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

    def fix(self, runner):
        if self.column_exists(table_name='MITARBEITER_POOL', column_name='USER_MV_CREATION') and \
                self.column_exists(table_name='MITARBEITER_POOL', column_name='PARALLEL_SESSIONS'):
            self.log('Columns already exists, so no need to add them again!')
            return self.success()

        for statement in self.STATEMENTS[self.DBMS]:
            self.modify_and_log(statement)

        return self.success()


class B_AddMissingColumnValuesInMP(SQLPacket):
    "Adding missing Column Values for columns created by A_AddMissingColumnsInMP"

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

    STATEMENT = "UPDATE MITARBEITER_POOL SET USER_MV_CREATION = 1 , PARALLEL_SESSIONS = 3 WHERE  STATUS IN (0,1)"

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

    def fix(self, runner):
        if self.column_exists(table_name='MITARBEITER_POOL', column_name='USER_MV_CREATION') and \
                self.column_exists(table_name='MITARBEITER_POOL', column_name='PARALLEL_SESSIONS'):
            self.modify_and_log(self.STATEMENT)
            return self.success()

        else:
            return self.fail('USER_MV_CREATION and/or PARALLEL_SESSIONS does not exist in the MITARBEITER_POOL table')
