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


class CreateWebInterfaceTables(SQLPacket):
    """Creates the new interface tables"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 19865

    sql_script = 'wi19865_create_web_interface_tables.sql'

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

    def fix(self, packet_runner):
        self.log('Trying to drop objects that could already exist')
        for datatable in (590, 591, 592, 593, 594, 595, 596):
            query = """ALTER TABLE DT{dt} DROP CONSTRAINT PID{dt}DT{dt}"""
            with suppress(ppms.DatabaseError):
                self.modify_and_log(query=query.format(dt=datatable), log_rows=False)

            query = """DROP INDEX PID{dt}DT{dt}"""
            with suppress(ppms.DatabaseError):
                self.modify_and_log(query=query.format(dt=datatable), log_rows=False)

        self.log('Now creating the new tables')
        self.apply_fix_ddl_file(self.sql_planta_de_dbms, self.sql_script, split=True)

        return self.success()
