import logging

from staff.lib import waffle
from django.views.decorators.http import require_GET

from staff.lib.decorators import (
    responding_json,
    use_request_lang,
    available_for_external,
)
from staff.person_profile.controllers import (
    badgepay,
)
from staff.person_profile.permissions.utils import observer_has_perm


logger = logging.getLogger(__name__)
BADGEPAY_SERVICE_ERROR = 'badgepday_service_error'


@require_GET
@available_for_external
@responding_json
@observer_has_perm('edoc')
@use_request_lang
def edoc(request, login):
    report = badgepay.get_short_food_report(login)
    if not report:
        return {}
    return {
        'target': {
            'food_balance_remaining_work_days': report.work_days_left,
            'food_balance_recommended': report.recommended_per_day,
            'food_balance_compensation_days': report.food_balance_compensation_days,
            'food_days_total': report.food_days_total,
            'food_balance_month': report.month_remained_sum,
            'food_balance_day': report.day_remained_sum,
            'food_limit_month': report.month_limit,
            'food_limit_day': report.day_limit,
            'food_overspending': report.overspending,
        }
    }


@require_GET
@available_for_external
@responding_json
@observer_has_perm('edoc')
@use_request_lang
def full_food_report(request, login):
    report = badgepay.get_full_food_report(login)
    if not report:
        return {'error': BADGEPAY_SERVICE_ERROR}
    return {
        'limit_month': report.limit_month,
        'limit_day': report.limit_day,
        'balance_month': report.remained_sum_month,
        'balance_day': report.remained_sum_day,
        'spent_per_day': report.middle_spent_per_day,
        'recommend_spent_per_day': report.recommended_per_day,
        'food_days_total': report.food_days_total,

        'working_days_left': report.work_days_left,
        'working_days_passed': report.work_days_passed,
        'overspending': report.overspending,
        'food_balance_compensation_days': report.food_balance_compensation_days,

        'orders': [
            {
                'date': order.date.isoformat(),
                'merchant': order.merchant,
                'amount': order.sum,
                'food': order.food,
                'breakfast': order.breakfast,
                'snack': order.snack,
                'money': order.money,
            }
            for order in report.orders
        ],

        'enable_snacks': waffle.switch_is_active('enable_snack'),
    }
