# -*- coding: utf-8 -*-
import itertools

from ppms import ppms
from ppms.migration.packet import *
from ppms.constants import *

__all__ = ['__RelationalConstraintsPacket__']

# Temporarily disabled
class __RelationalConstraintsPacket__(SQLPacket):
    '''Add relational constraints to the database.

    Only done for Q1B and Q2B data tables.
    Might encounter DatabaseErrors because of corrupt data,
    for more information see logfile.
    '''
    wi_number = 10246
    version = 1
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_HELPER

    def fix(self, runner):
        dialect = ppms.db_get_current_dialect()

        # Oracle Statements end on a ;
        if self.DBMS == DBMS_ORACLE:
            cutter = 1
        # MSSLQ Statements end on a GO
        elif self.DBMS == DBMS_MSSQL:
            cutter = 2
        else:
            raise NotImplementedError(self.DBMS)

        stmt = "SELECT DI000216 FROM DT415 WHERE DI000266 IN ('Q1B', 'Q2B')"
        table_names = list(itertools.chain(*ppms.db_select(stmt)))

        # TODO: Exclude views and similar?
        drop_list = ppms.db_custom_schema_create(dialect, table_names, False, False, True)
        create_list = ppms.db_custom_schema_create(dialect, table_names, True, False, True)

        failed_create_statements = 0

        self.log_heading('Performing drop statements')
        for drop_stmt in drop_list:
            statement = drop_stmt.strip()[:-cutter]
            try:
                self.modify_and_log(statement, log_rows=False)
            except ppms.DatabaseError as err:
                self.log(err)
                self.log('Might be that this constraint was simply non-existant.')

        ppms.db_commit()
        self.log_heading('DONE')

        self.log_heading('Performing create statements')
        for create_stmt in create_list:
            statement = create_stmt.strip()[:-cutter]
            try:
                self.modify_and_log(statement, log_rows=False)
            except ppms.DatabaseError as err:
                self.log(err)
                self.log('Ignoring for now')
                failed_create_statements += 1

        self.log_heading('DONE')

        if failed_create_statements:
            return self.fail('Failed %i create statements' % failed_create_statements)

        return self.success()
