# coding: utf-8


from contextlib import contextmanager

from django.conf import settings
from django.db import DatabaseError
from django.utils.timezone import now

from idm.core.utils import create_or_update_model
from idm.core.models import CommandTimestamp


@contextmanager
def timestamp_context(command_name, log):
    start = now()
    yield
    finish = now()
    try:
        if not settings.ENABLE_COMMAND_MONITORING:
            log.info('Task started at %s and finished at %s', start.isoformat(), finish.isoformat())
            return
        create_or_update_model(
            model=CommandTimestamp,
            obj_filter={'command': command_name},
            defaults={
                'last_success_start': start,
                'last_success_finish': finish,
            }
        )
    except DatabaseError:
        log.exception('Can\'t save timestamp for command %s to database', command_name)
