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

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


class UpdatePeriodAggregationQuery(ChangeDTPPacket):
    """Update the period aggregation query

    The 5 factors were not correctly aggregated to the parent across multiple
    levels. This migration packet fixes the queries and aggregates the period in the system.
    """

    helper_packet_path = 'migration.server.special.aggregate_resource_periods.AggregateResourcePeriods'
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 15815

    NEW_FILENAMES = {DBMS_ORACLE: ('aggregation_oracle_new.sql', 'summarize_oracle_new.sql'),
                     DBMS_MSSQL: ('aggregation_mssql_new.sql', 'summarize_mssql_new.sql')}

    OLD_FILENAMES = {DBMS_ORACLE: ('aggregation_oracle_old.sql', 'summarize_oracle_old.sql'),
                     DBMS_MSSQL: ('aggregation_mssql_old.sql', 'summarize_mssql_old.sql')}

    QUERIES = ('000682', '000691')

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

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

        old_filenames = self.OLD_FILENAMES.get(dbms, None)
        new_filenames = self.NEW_FILENAMES.get(dbms, None)

        if old_filenames is None or new_filenames is None:
            return self.fail('Unknown dbms!!')

        for old_filename, new_filename, query in zip(old_filenames, new_filenames, self.QUERIES):
            old_file_path = os.path.join(os.path.dirname(__file__), old_filename)
            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()

            with open(old_file_path, 'r') as f:
                old_statement = f.read()

            record = self.get_record(343, [dbms, query], ['source_text_clob'])
            if not self.change_value(record, 'source_text_clob', old_statement, new_statement):
                return self.fail('Changing the update query failed')

        self.reset_cleanup_helper()
        return self.success()


    def reset_cleanup_helper(self):
        self.mark_packet_as_undone(self.helper_packet_path)


    def mark_packet_as_undone(self, packet_path):
        future_packet = BasePacket.from_packet_path(packet_path)
        if future_packet is None:
            self.log('No packet with path "%s" found - might be a problem!' % packet_path)
            return False

        self.log('Marking the packet with path "%s" as undone' % packet_path)
        future_packet.log('Packet marked as undone by "%s"' % str(self))
        future_packet.mark_as_undone()
        future_packet.save_history()

        return True
