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


class CorrectSchemaDefinitionVenus(SQLPacket):
    """Correct TEMP_PERIOD_CHANGES to use 20 CHAR instead of 20 BYTE"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 20462

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

    # noinspection PyMethodOverriding
    def get_char_length_of_varchar_column(self, table_name, column_name):
        dbms = ppms.db_get_dbms_name()
        if dbms == DBMS_ORACLE:
            char_length_stmt = r"""select CHAR_LENGTH from USER_TAB_COLUMNS
                                 where
                                   TABLE_NAME = '{table_name}'
                                   AND COLUMN_NAME = '{column_name}'""".format(table_name=table_name,
                                                                               column_name=column_name)

            return ppms.db_select(char_length_stmt)[0][0]

        raise NotImplementedError(dbms)

    # noinspection PyMethodOverriding
    def get_varchar_column_type(self, table_name, column_name):
        """Get the varchar column type

        Returns B for bytes and C for char
        """
        dbms = ppms.db_get_dbms_name()
        if dbms == DBMS_ORACLE:
            char_length_stmt = r"""select CHAR_USED from USER_TAB_COLUMNS
                                 where
                                   TABLE_NAME = '{table_name}'
                                   AND COLUMN_NAME = '{column_name}'""".format(table_name=table_name,
                                                                               column_name=column_name)

            return ppms.db_select(char_length_stmt)[0][0]

        raise NotImplementedError(dbms)

    def fix(self, packet_runner):
        if self.DBMS != DBMS_ORACLE:
            self.log('Schema should already be correct in this system')
            return self.success()

        column_type = self.get_varchar_column_type(table_name='TEMP_PERIOD_CHANGES', column_name='RES_ID')
        char_length = self.get_char_length_of_varchar_column(table_name='TEMP_PERIOD_CHANGES', column_name='RES_ID')

        if column_type == 'C' and char_length >= 20:
            self.log('System already looks OK')
            return self.success()

        if column_type == 'B' or (column_type == 'C' and char_length < 20):
            char_length = max(20, char_length)
            query = "ALTER TABLE TEMP_PERIOD_CHANGES MODIFY (RES_ID VARCHAR2({} CHAR))".format(char_length)
            self.modify_and_log(query, log_rows=False)

        else:
            return self.fail('Unexpected column type: {}'.format(column_type))

        return self.success()
