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

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


class FixStatisticsTable(SQLPacket):
    '''Add column for memory usage and fix column type for DI059758'''

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

    SQL = 'WI13090_fix_statistics_table.sql'

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

    def fix(self, runner):
        success_experienced = False
        failure_experienced = False

        sqlpath = self.get_sql_file_path(self.sql_planta_de_dbms, self.SQL)

        queries = self.get_queries_from_file(sqlpath)

        for query in queries:
            try:
                self.modify_or_log(query)
                success_experienced = True
            except:
                failure_experienced = True

        if failure_experienced:
            if success_experienced:
                self.log('Partial failure - not all statements could be applied to the DB! Please see above for details.')
            else:
                self.log('Complete failure - not a single statement could be applied to the DB! Package being executed for the second time?')
            return self.fail()
        else:
            return self.success()


class FixStatisticsTableValueRanges(ChangeDTPPacket):
    '''Adjust value ranges of DIs 004385 and 057710'''

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

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

    def fix(self, runner):
        dis = {'004385':('', """# time_dtp_selection_real

from ppms import ppms

def computeOutput(di):
    record = di.get_dtp_record()
    return di.get_value() - record.time_db_wait.get_value()

computeOutput.deps = (
    "DI004381", # time_db_wait
)
"""),
               '057710':("""# unspecified_real_time

from ppms import ppms

def computeOutput(di):
    record = di.get_dtp_record()
    return (
          record.entire_event_real.get_value()
        - record.time_db_wait.get_value()
        - record.time_dtp_selection_real.get_value()
    )

computeOutput.deps = (
    "DI004371", # entire_event_real
    "DI004381", # time_db_wait
    "DI004385", # time_dtp_selection_real
)""", """# unspecified_real_time

from ppms import ppms

def computeOutput(di):
    record = di.get_dtp_record()
    return (
          record.entire_event_real.get_value()
        - record.time_db_wait.get_value()
        - record.time_dtp_selection_real.get_value()
        - record.time_mts_creation.get_value()
        - record.time_xml_output.get_value()
    )

computeOutput.deps = (
    "DI004371", # entire_event_real
    "DI004381", # time_db_wait
    "DI004385", # time_dtp_selection_real
    "DI022750", # time_mts_creation
    "DI040544", # time_xml_output
)""")}
        for di, (old_value, new_value) in dis.items():
            record = self.get_record(412, [di], ['valuerange'])
            if not self.change_value(record, 'valuerange', old_value, new_value):
                return self.fail()
        
        record = self.get_record(412, ['004385'], ['wb_type'])
        if not self.change_value(record, 'wb_type', '', 'PY'):
            return self.fail()

        return self.success()
