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

from distutils.version import StrictVersion
import os

from ppms.migration import PacketCategory, MaxVersionDependency
from ppms import ppms
from ppms.migration import SQLPacket, MinVersionDependency, VersionType


class BaseDisableSystemCustomizing():
    generated_sql_file = '''wi13741_disable_system_customizing.sql'''


class DisableSystemCustomizingGenerator(BaseDisableSystemCustomizing, SQLPacket):
    def fix(self, packet_runner):
        pass


    def to_file(self):
        self.update_statements = list()
        self.gather_update_statements()
        with open(self.get_sql_file_path(self.sql_planta_de_ansi, self.generated_sql_file), 'w') as f:
            for stmt in self.update_statements:
                f.write(stmt)


    def gather_update_statements(self):
        if MinVersionDependency.get_customizing_version() < StrictVersion('39.5'):
            ppms.cu_message_box('This is supposed to run in Venus only! Aborting.')
            return
        else:
            self.collect_disabled_db_schemas()
            self.collect_disabled_data_tables()


    def collect_disabled_db_schemas(self):
        self.collect_disabled_objects('dt420', 'di000289')


    def collect_disabled_data_tables(self):
        self.collect_disabled_objects('dt415', 'di000265')


    def collect_disabled_objects(self, table_sql_name, id_column_sql_name):
        objects = self.select_or_log("""select {c} from {t} where enabled = 0 order by {c}"""
                                     .format(c=id_column_sql_name, t=table_sql_name))
        object_ids = [o[0] for o in objects]
        update_stmt = """update {t}\nset enabled = 0\nwhere {c} in (\n  '{in_list}');\n\n""" \
            .format(c=id_column_sql_name, t=table_sql_name,
                    in_list="""',\n  '""".join(object_ids))
        self.update_statements.append(update_stmt)


class DisableObsoleteSystemCustomizing(SQLPacket, BaseDisableSystemCustomizing):
    """Disable some obsolete system customizing objects
    """

    version = 1
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13741

    dml_file = 'wi13741_disable_cu_without_db_objects.sql'
    ddl_file = 'wi13741_fix_db_objects_according_to_cu.sql'

    veto_tables = [836]
    veto_stmt = """update dt415 set enabled = 1 where di000265 = '{dt:03d}'"""


    def get_dependencies(self):
        return (MaxVersionDependency(version='39.4.0', version_type=VersionType.CUSTOMIZING))


    def fix(self, runner):
        try:
            # disable all DB schemas and data tables which are inactive in Venus
            self.apply_dml_file(self.sql_planta_de_ansi, self.generated_sql_file)

            # some of those tables are still required in VoE, though
            for table in self.veto_tables:
                stmt = self.veto_stmt.format(dt=table)
                self.modify_and_log(stmt)

            # disable additional CU objects without any underlying DDL equivalent
            self.apply_dml_file(self.sql_planta_de_ansi, self.dml_file)

            # make DDL match system customizing
            self.apply_fix_ddl_file(self.sql_planta_de_dbms, self.ddl_file, split=True)

            return self.success()
        except Exception as e:
            self.fail(e)
