import logging

from django.conf import settings

from staff.celery_app import app
from staff.lib.log import log_context
from staff.lib.tasks import LockedTask
from staff.lib.utils.date import get_timedelta_setting

from staff.trip_questionary.models import TripQuestionaryCollection
from staff.trip_questionary.controller.operations.registry import run_operations
from staff.trip_questionary.monitor import get_sync_timeouted_query


logger = logging.getLogger(__name__)


@app.task
class TripAsyncOperator(LockedTask):
    def locked_run(self, trip_uuid, comment_author_id=None):
        try:
            with log_context(trip_uuid=trip_uuid):
                trip = TripQuestionaryCollection().get(uuid=trip_uuid)
                logger.info('Running trip operations')
                run_operations(trip)
        except Exception as exc:
            raise self.retry(countdown=60, exc=exc)

    def get_lock_name(self, trip_uuid, **kwargs):
        return 'trip_async_operator_{}'.format(trip_uuid)


trip_async_operator = TripAsyncOperator


@app.task
class SyncWithStartrek(LockedTask):
    def locked_run(self, *args, **kwargs):
        q = get_sync_timeouted_query(get_timedelta_setting('PEAK_PROTECTION_INTERVAL'))

        trip_list = TripQuestionaryCollection().find(q)

        for trip in trip_list:
            trip_async_operator.apply_async(
                args=[trip.uuid],
                queue=settings.CELERY_TRIPS_QUEUE,
            )


sync_with_startrek = SyncWithStartrek
