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

class FixHistogramDfStructuralAggregation(SQLPacket):
    '''Move non-zero aggregation type to proper structural aggregation toggle.

    There was a workaround in Earth for the lack of structural aggregation.
    Histogram Bar DFs where aggregation type was non-empty would aggregate
    across structured records, whereas empty aggregation type would avoid
    that, for instance when data is pre-aggregated in DB such as in DT 468.

    This package will port the former workaround to the newly established
    permanent solution. Structure Aggregation as of DI 000106 now also
    concerns Histogram Bar DFs.
    '''
    version = 1
    done_after_success = True
    run_on_startup = True
    wi_number = 11100
    category = PacketCategory.CATEGORY_MANDATORY

    def fix(self, runner):
        query_clear = '''UPDATE DT411 SET DI000106 = 0
        WHERE DI000288 = 0
        AND EXISTS (
            SELECT 1 FROM DT412
            WHERE DI000238 = DI000213 AND DI001700 = 2)'''

        query_set = '''UPDATE DT411 SET DI000106 = 1, DI000288 = 0
        WHERE DI000288 > 0 AND EXISTS (
            SELECT 1 FROM DT412
            WHERE DI000238 = DI000213 AND DI001700 = 2)'''

        self.log("Porting Histogram Bar DF structure aggregation from former workaround to permanent solution.")
        self.modify_and_log(query_clear)
        self.modify_and_log(query_set)
        return self.success()
