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

from ppms import ppms
from ppms.constants import *
from ppms.migration import BasePacket, ChangeDTPPacket, MaxVersionDependency, PacketCategory


class FixPeriodAggregationQuery(ChangeDTPPacket):
    """Update the period aggregation query and sets the most likely failed S24 packet to done."""

    old_packet_path = 'migration.server.S_39_5_24.WI21117_fix_period_aggregation.FixPeriodAggregationQuery'
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 21476

    NEW_FILENAME = {DBMS_ORACLE: 'aggregation_oracle_new.sql',
                     DBMS_MSSQL: 'aggregation_mssql_new.sql'}

    QUERIE = '000682'

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

    def fix(self, runner):
        dbms = ppms.db_get_dbms_name()

        new_filename = self.NEW_FILENAME.get(dbms, None)
        if new_filename is None:
            return self.fail('Unknown DBMS!')

        new_file_path = os.path.join(os.path.dirname(__file__), new_filename)

        self.log('Updating period query from file: "%s"' % new_file_path)
        with open(new_file_path, 'r') as f:
            new_statement = f.read()

        record = self.get_record(343, [dbms, self.QUERIE], ['source_text_clob'])
        self.log(
            "The old query was:\n{old_value}\n\nUpdating it now.".format(old_value=record.source_text_clob.get_value()))
        if not self.change_value(record, 'source_text_clob', None, new_statement):
            return self.fail('Changing the update query failed')

        self.mark_packet_as_done(self.old_packet_path)
        return self.success()

    def mark_packet_as_done(self, packet_path):
        old_packet = BasePacket.from_packet_path(packet_path)
        if old_packet.done:
            self.log("Packet with path {path} already maked as done, nothing to do!".format(path=packet_path))
            return True
        if old_packet is None:
            self.log('No packet with path "%s" found - might be a problem!' % packet_path)
            return False

        self.log('Marking the old packet with path "%s" as done' % packet_path)
        old_packet.log('Packet marked as undone by "%s".' % str(self))
        old_packet.mark_as_done()
        old_packet.save_history()

        return True
