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

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


class FixPeriodAggregationQuery(ChangeDTPPacket, SQLPacket):
    """Update the period aggregation query"""

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

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

    CREATE_QUERY_SQL = 'wi21117_period_creation_and_aggregation.sql'

    QUERY = '000682'

    def query_exists(self, query):
        """Check if a query (DT342) already exists."""
        query_exists_in_db = self.select_or_log(
            "select count(*) from DT342 where DI024359 = '{query}'".format(query=query))
        return bool(query_exists_in_db[0][0])

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

    def create_sql_query(self):
        self.log('Creating the missing query now')
        self.apply_dml_file(self.sql_planta_de_dbms, self.CREATE_QUERY_SQL)

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

        # we are updating a VoE system where the query does not exist yet... so creating it here
        if self.query_exists(self.QUERY):
            self.create_sql_query()

        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.QUERY], ['source_text_clob'])

        self.log(
            "The old query was:\n {old_value}\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.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
