import logging

from staff.celery_app import app
from staff.lib.db import atomic
from staff.lib.tasks import LockedTask


logger = logging.getLogger(__name__)


@app.task
class UpdatePersonsFilters(LockedTask):
    def locked_run(self, filter_ids=None, *args, **kwargs):
        from .saved_filter_ctl import PersonsFilterCtl

        if filter_ids is None:
            ctls = PersonsFilterCtl.get_update_candidates()
        else:
            ctls = (PersonsFilterCtl.get_by_filter_id(f_id) for f_id in filter_ids)

        for person_filter_ctl in ctls:
            try:
                with atomic():
                    person_filter_ctl.update()
            except Exception:
                logger.exception(
                    'When update PersonsFilter %d',
                    person_filter_ctl.persons_filter.id
                )
