# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2017-03-30 06:18
from __future__ import unicode_literals

import logging

from django.db import migrations


logger = logging.getLogger(__name__)


def create_missing_commitments(apps, *args):
    """
    For activities that have a non-null total_budget and 0 commitments,
    create a commitment that equals the total_budget.

    Following the IATI standard, we are migrating the 'Total Budget' to a 'Total Commitment'.
    """
    Activity = apps.get_model('aims', 'Activity')
    Transaction = apps.get_model('aims', 'Transaction')

    activities = Activity.objects.filter(total_budget__gt=0)
    for activity in activities:
        if activity.transaction_set.filter(transaction_type_id='C').exists():
            continue

        currency_id = activity.total_budget_currency_id or activity.default_currency_id
        if currency_id is None:
            # budget without a currency, we can't process that
            continue

        start_date = activity.start_actual or activity.start_planned
        value = activity.total_budget

        # determine the provider and receiver for the transaction
        funding_organisations_ids = activity.transaction_set.filter(provider_organisation__isnull=False)\
            .values_list('provider_organisation_id', flat=True).distinct()
        if len(funding_organisations_ids) == 1 and funding_organisations_ids[0] == activity.reporting_organisation_id:
            provider_id = activity.reporting_organisation_id
            implementing_organisations = activity.participating_organisations.filter(role_id='Implementing')
            if len(implementing_organisations) == 1:
                receiver_id = implementing_organisations[0].organisation_id
            else:
                receiver_id = None
        elif len(funding_organisations_ids) == 1 and funding_organisations_ids[0] != activity.reporting_organisation_id:
            # should be filled out by Leigh
            provider_id = None
            receiver_id = None
        elif len(funding_organisations_ids) == 0:
            provider_id = activity.reporting_organisation_id
            receiver_id = activity.reporting_organisation_id
        else:
            # this case does not exist in the Mohinga production db as of 2017-04-12
            assert len(funding_organisations_ids) > 1
            provider_id = None
            receiver_id = None

        transaction = Transaction.objects.create(
            activity=activity,
            transaction_type_id='C',
            transaction_date=start_date,
            value_date=start_date,
            value=value,
            currency_id=currency_id,
            provider_organisation_id=provider_id,
            receiver_organisation_id=receiver_id,
            aid_type_id=activity.default_aid_type_id,
            finance_type_id=activity.default_finance_type_id,
            flow_type_id=activity.default_flow_type_id,
            tied_status_id=activity.default_tied_status_id
        )
        logger.debug('created transaction {}'.format(transaction))


def populate_total_commitment(apps, *args):
    """ For all activities that have commitments, save the total_commitment. """
    # import directly because the faked model returned by apps.get_model() doesn't have the total_commitment field
    from ..models import Activity
    for activity in Activity.objects.filter(transaction__transaction_type_id='C'):
        activity.set_total_commitment()


class Migration(migrations.Migration):

    dependencies = [
        ('aims', '0046_move_oldaims_iati'),
    ]

    operations = [
        # migrations.RunPython(create_missing_commitments, reverse_code=migrations.RunPython.noop),
        # migrations.RunPython(populate_total_commitment, reverse_code=migrations.RunPython.noop),
    ]
