# -*- coding: utf-8 -*-
from ppms import ppms
from ppms.constants import *
from ppms.migration import *


def table_exists(table_name):
    """Check if a table exists"""
    dbms = ppms.db_get_dbms_name()

    if dbms == DBMS_ORACLE:
        query = """SELECT count(*) FROM user_tables
                   WHERE
                     table_name = '{table_name}'"""

    elif dbms == DBMS_MSSQL:
        query = """SELECT COUNT(*) FROM sys.tables
                   WHERE
                     Object_ID = Object_ID(N'{table_name}')"""

    else:
        raise NotImplementedError(dbms)

    return ppms.db_select(query.format(table_name=table_name))[0][0] == 1


class A_PortPythonProfilerToVenusOnEarthSchema(SQLPacket):
    """Ports the Python profiler tables (schema) down for Venus on Earth"""
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 18938

    filename_performance_table = 'wi18938_performance_table.sql'
    filename_function_call_table = 'wi18938_function_call_table.sql'

    def get_dependencies(self):
        return MaxVersionDependency(version='39.4'),

    def insert_performance_table(self):
        self.log_heading('Inserting table PYTHONPERFORMANCE')
        self.apply_dml_file(self.sql_planta_de_dbms, self.filename_performance_table)

    def insert_function_call_table(self):
        self.log_heading('Inserting table PYTHONFUNCTIONCALL')
        self.apply_dml_file(self.sql_planta_de_dbms, self.filename_function_call_table)

    def fix(self, runner):
        if not table_exists(table_name='PYTHONPERFORMANCE'):
            with ppms.autocommit_disabled():
                self.insert_performance_table()

        if not table_exists(table_name='PYTHONFUNCTIONCALL'):
            with ppms.autocommit_disabled():
                self.insert_function_call_table()

        return self.success()


class B_PortPythonProfilerToVenusOnEarthCustomizing(SQLPacket):
    """Port the new Python profiler to Venus on Earth"""
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 18938

    filename = 'wi18938_port_python_profiler.sql'
    deletion_file = 'wi18938_port_python_profiler_delete.sql'

    def get_dependencies(self):
        return MaxVersionDependency(version='39.4'),

    def delete_old_data(self):
        self.log_heading('Wiping data that could cause conflicts')
        self.apply_dml_file(self.sql_planta_de_ansi, self.deletion_file)

    def insert_new_data(self):
        self.log_heading('Inserting new data')
        self.apply_dml_file(self.sql_planta_de_dbms, self.filename)

    def fix(self, runner):
        with ppms.autocommit_disabled():
            self.delete_old_data()
            self.insert_new_data()

        return self.success()
