from intranet.femida.src.celery_app import app

from intranet.femida.src.actionlog.tasks import touch_candidates_task
from intranet.femida.src.attachments.models import Attachment
from intranet.femida.src.candidates.models import CandidateAttachment
from intranet.femida.src.isearch.tasks import bulk_push_candidates_to_isearch


@app.autoretry_task(max_retries=3)
def extract_text_for_attachments(attachment_ids):
    attachments = Attachment.objects.filter(id__in=attachment_ids, text__isnull=True)
    for attachment in attachments:
        attachment.extract_text()
        attachment.save()

    candidate_ids = list(set(
        CandidateAttachment.unsafe
        .filter(attachment_id__in=attachment_ids)
        .values_list('candidate_id', flat=True)
    ))
    touch_candidates_task.delay(candidate_ids)
    bulk_push_candidates_to_isearch.delay(candidate_ids)
