# coding: utf-8

from datetime import datetime, timedelta

import constance
from django.db.models import Q

from idm.core.models import Action
from idm.monitorings.views.base import BaseMonitoringView


class GapSynchronizationErrorsView(BaseMonitoringView):
    """
        Ошибки синхронизации с Гэпом за последний час
    """
    def monitoring(self):
        errors = []
        hour_ago = datetime.utcnow() - timedelta(hours=constance.config.GAP_MONITORING_TIMEDELTA)
        recently_failed_gap_sync_actions = (
                Q(action='gap_synchronization_completed') &
                ~Q(error__exact='') &
                Q(added__gte=hour_ago)
        )
        last_action = Action.objects.filter(recently_failed_gap_sync_actions).values('error', 'added').first()
        if last_action:
            error_template = "[{}] => Exception message: {}"
            errors.append(error_template.format(
                last_action['added'].replace(microsecond=0, tzinfo=None).isoformat(),
                last_action['error'])
            )

        return errors
