# -*- coding: utf-8 -*-

from ppms.migration import SQLPacket, PacketCategory
from ppms import ppms
from ppms.constants import *


class ActivateAndMoveCustomerTablesToCustomerSchema(SQLPacket):
    '''Activates and Moves Customer tables to the right schema

    Activates and Moves DT 150,151,152,153 to the right schema
    '''
    wi_number = 18564
    done_after_success = False
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY

    def fix(self, runner):
        for DT_name in ['DT150', 'DT151', 'DT152', 'DT153']:
            dt_exists_query ={DBMS_MSSQL:"""SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{DT_name}'""",
                              DBMS_ORACLE:"""SELECT COUNT(*) FROM user_tables WHERE TABLE_NAME = '{DT_name}'"""}
            enable_query = """UPDATE DT415 SET ENABLED = 1 WHERE DI000216= '{DT_name}'"""
            table_index_query = """SELECT DI000289, DI001554, DI001555, DI008075, DI008149 FROM DT420
                WHERE NOT DI000289 = 'K000' AND DI000289 LIKE 'K%'"""
            move_table_query = """UPDATE DT415 SET DI000266='{schema_name}' WHERE DI000216= '{DT_name}'"""

            dt_exists = ppms.db_select(dt_exists_query[self.DBMS].format(DT_name=DT_name))[0][0]

            if dt_exists:
                self.modify_and_log(enable_query.format(DT_name=DT_name))
                self.log("Enabled " + DT_name)

                for schema in ppms.db_select(table_index_query):
                    schema_name = schema[0]
                    if (DT_name == "DT150" and schema[1] == '008214') or \
                            (DT_name == "DT151" and schema[2] == '008245') or \
                            (DT_name == "DT152" and schema[3] == '008247') or \
                            (DT_name == "DT153" and schema[4] == '008263'):
                        self.modify_and_log(move_table_query.format(schema_name=schema_name, DT_name=DT_name))
                        self.log("Moved " + DT_name + " to Schema " + schema_name)

        return self.success()
