import logging

from core.utils import dtnow
from inputs.models import LogInput
from inputs.services.inputs import get_sensor

_log = logging.getLogger(__name__)


def parse_endpoint_celery_done_events(hit):
    """ Function for parsing Endpoint events with `celery_done` field set to False.
        This function check several things:
            1) Check if initiated scan has been finished on antivirus.
                If true -> set scan_in_progress endpoint flag to false
            2) Check if AV DB update was successful. If true -> update last_av_db_update endpoint field to correct valdtnow()
    :param hit: event from elasticsearch. Must be for ARMA IE only
    """
    sign_subcategory = hit['_source']['sign_subcategory']
    endpoint = hit['_source']['type']
    # Parse update events
    if sign_subcategory == 'UPDATE STATUS' and 'FILE UPDATED' in hit['_source']['event_src_msg']:
        try:
            _, sensor = get_sensor(endpoint)
            sensor.clamav_last_update = dtnow()
            sensor.save()
        except LogInput.DoesNotExist:
            _log.error(f'Endpoint, corresponding to {endpoint} does not exist')