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


class AddSchemaExtensions(SQLPacket):
    """
    Adds indices and constraints which are not included int the automatically generated schema.

    The packet reads all files from schema_extensions folder and executes all statements from these files.
    """

    version = 1
    done_after_success = False
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 17822

    directories = {DBMS_MSSQL: "mssql", DBMS_ORACLE: "oracle"}

    def fix(self, runner):
        path = os.path.join(os.getcwd(), "migration", "after_db_import", "DB_39_5_7", "schema_extensions", self.directories[self.DBMS])
        for directory, subdirectories, file_names in os.walk(path):
            self.log("Found the following sql files: \n" + str(file_names))
            for file in file_names:
                # only execute .sql files
                if not file.upper().endswith(".SQL"):
                    continue
                if self.DBMS == DBMS_ORACLE:
                    separator = ";\/[ ]*$"
                else:
                    separator = "GO[ ]*$"
                for query in self.get_queries_from_file(os.path.join(directory, file), split=True, separator=separator):
                    try:
                        if not self.change_create_index_to_rename_index(query):
                            self.modify_and_log(query)
                    except ppms.DatabaseError:
                        pass

        return self.success()