import logging


from staff.lib.decorators import responding_json
from staff.trip_questionary.models import TripQuestionaryCollection
from staff.trip_questionary.monitor import get_slowpoke_query

ISSUE_CREATION_MONITORING_INTERVAL = 60 * 60  # 60 minutes
logger = logging.getLogger('monitoring.trips')


def _trip_record(trip_questionary_model):
    trip_data = trip_questionary_model.get_dehydrated_data()
    trip_data.pop('_id')
    return trip_data


@responding_json
def check_problem_trips(request):
    slowpoke_delay = int(request.GET.get('delay', ISSUE_CREATION_MONITORING_INTERVAL))
    problem_trips = (
        TripQuestionaryCollection().find(
            get_slowpoke_query(seconds=slowpoke_delay)
        )
    )

    problem_trips = {
        trip.uuid: _trip_record(trip)
        for trip in problem_trips
    }

    if problem_trips:
        logger.warning(
            'There are %s problem trips with no tickets created: %s',
            len(problem_trips),
            list(problem_trips.keys()),
        )
    return problem_trips
