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

from planta_logging.logging import *
from ppms import ppms
from ppms.constants import *
from ppms.migration import BasePacket, PacketCategory, PacketDependency, PacketState
from ppms.period import aggregate_periods_from_start_to_end
from ppms.ressource import get_all_ressources_of_department


class AggregateResourcePeriods(BasePacket):
    """A special packet that encapsulates the resource period aggregation

    This used to be performed by any packet that changed the rules of
    aggregation. Since the operation is very time consuming, and might be
    desirable for a user to invoke explicitly, a separate helper packet is now
    available for your convenience.
    """

    special_snowflake = True
    run_on_startup = False  # This packet is very time consuming and should only be invoked willingly
    done_after_success = True
    category = PacketCategory.CATEGORY_HELPER
    wi_number = 20955


    def fix(self, runner):
        all_resources = list(itertools.chain(*ppms.db_select("SELECT DI001218 FROM DT467")))
        resources_to_aggregate = all_resources[:]

        # Only call the period aggregation for the lowest level children
        # as those will aggregate to the top anyway
        for resource_id in all_resources:
            child_resources = get_all_ressources_of_department(resource_id, skip_departments=False)

            for child_resource in child_resources:
                if child_resource in resources_to_aggregate:
                    resources_to_aggregate.remove(resource_id)
                    break

        apology = 'Now running the period aggregation for all resources in the system. This could take a while!'
        self.log_heading(apology)

        log_write(LogLevel.INFO, ComponentID.PY_PLANTA_DE, "UpdatePeriodAggregationQuery", -1, 'operative', '',
                  apology)

        for index, resource_id in enumerate(resources_to_aggregate):
            status_update = 'Working on resource %d of %d' % (index + 1, len(resources_to_aggregate))
            log_write(LogLevel.INFO, ComponentID.PY_PLANTA_DE, "UpdatePeriodAggregationQuery", -1, 'operative', '',
                      status_update)

            aggregate_periods_from_start_to_end(resource_id)

        self.log('Done with the aggregation.')
        return self.success()
