# Path: django_datawatch/backends/base.py
# class BaseBackend(object):
#     def enqueue(self, slug, run_async=True):
#         raise NotImplementedError('enqueue not implemented')
# 
#     def refresh(self, slug, run_async=True):
#         raise NotImplementedError('refresh not implemented')
# 
#     def run(self, slug, identifier, run_async=True, user_forced_refresh=False):
#         raise NotImplementedError('run not implemented')
# 
# Path: django_datawatch/models.py
# class Result(TimeStampedModel):
#     STATUS = Choices((0, 'unknown', _('Unknown')),
#                      (1, 'ok', _('OK')),
#                      (2, 'warning', _('Warning')),
#                      (3, 'critical', _('Critical')))
# 
#     slug = models.TextField(verbose_name=_('Module slug'))
#     identifier = models.CharField(max_length=256, verbose_name=_('Identifier'))
# 
#     status = models.IntegerField(choices=STATUS,
#                                  default=STATUS.unknown, verbose_name=_('Status'))
#     data = JSONField(blank=True, default=dict, verbose_name=('Data'))
#     config = JSONField(blank=True, default=dict, verbose_name=_('Configuration'))
# 
#     payload_description = models.TextField(verbose_name=_('Payload description'))
# 
#     acknowledged_by = models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, blank=True,
#                                         verbose_name=_('Acknowledged by'),
#                                         related_name='acknowledged_by', on_delete=models.CASCADE)
#     acknowledged_at = models.DateTimeField(null=True, blank=True, verbose_name=_('Acknowledged at'))
#     acknowledged_until = models.DateTimeField(null=True, blank=True, verbose_name=_('Acknowledged until'))
#     acknowledged_reason = models.TextField(blank=True, verbose_name=_('Acknowledge reason'))
# 
#     assigned_to_user = models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, blank=True,
#                                          related_name='assigned_to_user', on_delete=models.SET_NULL)
#     assigned_to_group = models.ForeignKey(to='auth.Group', null=True, blank=True, on_delete=models.SET_NULL)
# 
#     objects = ResultQuerySet.as_manager()
# 
#     class Meta:
#         unique_together = ('slug', 'identifier')
#         permissions = (('view', 'Can view results dashboard and details'), ('acknowledge', 'Can acknowledge results'),
#                        ('config', 'Can change the configuration for results'), ('refresh', 'Can refresh results'))
# 
#     def acknowledge(self, user, days, reason=None, commit=True):
#         # calculate end of requested acknowledgement
#         acknowledged_until = timezone.now() + relativedelta.relativedelta(days=days)
# 
#         # check that we're not accidentally overriding the current setup
#         if self.status in (self.STATUS.warning, self.STATUS.critical):
#             if self.is_acknowledged() and self.acknowledged_until > acknowledged_until:
#                 raise AlreadyAcknowledged()
#         self.acknowledged_at = timezone.now()
#         self.acknowledged_by = user
#         self.acknowledged_until = acknowledged_until
#         self.acknowledged_reason = reason or ''
#         if commit:
#             self.save(update_fields=['acknowledged_at', 'acknowledged_by', 'acknowledged_until', 'acknowledged_reason'])
# 
#     def is_acknowledged(self):
#         return self.acknowledged_until and self.acknowledged_until >= timezone.now()
# 
#     def __str__(self):
#         return self.slug
# 
#     def get_check_instance(self):
#         return datawatch.get_check_class(self.slug)()
# 
#     def get_payload(self):
#         return self.get_check_instance().get_payload(self.identifier)
# 
#     def get_formatted_data(self):
#         return datawatch.get_check_class(self.slug)().format_result_data(self)
# 
#     def latest_status(self, status):
#         return self.status_history.filter(to_status=status).order_by('-created').first()
# 
#     @cached_property
#     def latest_unknown(self):
#         return self.latest_status(self.STATUS.unknown)
# 
#     @cached_property
#     def latest_ok(self):
#         return self.latest_status(self.STATUS.ok)
# 
#     @cached_property
#     def latest_warning(self):
#         return self.latest_status(self.STATUS.warning)
# 
#     @cached_property
#     def latest_critical(self):
#         return self.latest_status(self.STATUS.critical)
# 
# Path: django_datawatch/datawatch.py
# class DatawatchHandler(object):
# class Scheduler(object):
#     def __init__(self):
#     def autodiscover_checks(self, module_name='checks'):
#     def register(self, check_class):
#     def get_all_registered_checks(self):
#     def get_all_registered_check_slugs(self):
#     def get_check_class(self, slug):
#     def get_checks_for_related_model(self, model):
#     def get_checks_for_model(self, model):
#     def get_slug(self, module, class_name):
#     def get_backend(self):
#     def delete_results(self, sender, instance):
#     def update_related(self, sender, instance):
#     def run_checks(self, force=False, slug=None):
#     def get_last_executions(self):
# def make_model_uid(model):
# def delete_results(sender, instance, using, **kwargs):
# def run_checks(sender, instance, created, raw, using, **kwargs):


import logging
from django.core.exceptions import ObjectDoesNotExist
from django_datawatch.backends.base import BaseBackend
from django_datawatch.models import Result
from django_datawatch.datawatch import datawatch
# -*- coding: UTF-8 -*-



logger = logging.getLogger(__name__)


class Backend(BaseBackend):
    def enqueue(self, slug, run_async=True):
        check = self._get_check_instance(slug)
        if not check:
            return

        try:
            for payload in check.generate():
                if payload is None:
                    continue
                datawatch.get_backend().run(check.slug, check.get_identifier(payload))
        except NotImplementedError as e:
            logger.error(e)

    def refresh(self, slug, run_async=True):

# Path: django_datawatch/backends/base.py
# class BaseBackend(object):
#     def enqueue(self, slug, run_async=True):
#         raise NotImplementedError('enqueue not implemented')
# 
#     def refresh(self, slug, run_async=True):
#         raise NotImplementedError('refresh not implemented')
# 
#     def run(self, slug, identifier, run_async=True, user_forced_refresh=False):
#         raise NotImplementedError('run not implemented')
# 
# Path: django_datawatch/models.py
# class Result(TimeStampedModel):
#     STATUS = Choices((0, 'unknown', _('Unknown')),
#                      (1, 'ok', _('OK')),
#                      (2, 'warning', _('Warning')),
#                      (3, 'critical', _('Critical')))
# 
#     slug = models.TextField(verbose_name=_('Module slug'))
#     identifier = models.CharField(max_length=256, verbose_name=_('Identifier'))
# 
#     status = models.IntegerField(choices=STATUS,
#                                  default=STATUS.unknown, verbose_name=_('Status'))
#     data = JSONField(blank=True, default=dict, verbose_name=('Data'))
#     config = JSONField(blank=True, default=dict, verbose_name=_('Configuration'))
# 
#     payload_description = models.TextField(verbose_name=_('Payload description'))
# 
#     acknowledged_by = models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, blank=True,
#                                         verbose_name=_('Acknowledged by'),
#                                         related_name='acknowledged_by', on_delete=models.CASCADE)
#     acknowledged_at = models.DateTimeField(null=True, blank=True, verbose_name=_('Acknowledged at'))
#     acknowledged_until = models.DateTimeField(null=True, blank=True, verbose_name=_('Acknowledged until'))
#     acknowledged_reason = models.TextField(blank=True, verbose_name=_('Acknowledge reason'))
# 
#     assigned_to_user = models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, blank=True,
#                                          related_name='assigned_to_user', on_delete=models.SET_NULL)
#     assigned_to_group = models.ForeignKey(to='auth.Group', null=True, blank=True, on_delete=models.SET_NULL)
# 
#     objects = ResultQuerySet.as_manager()
# 
#     class Meta:
#         unique_together = ('slug', 'identifier')
#         permissions = (('view', 'Can view results dashboard and details'), ('acknowledge', 'Can acknowledge results'),
#                        ('config', 'Can change the configuration for results'), ('refresh', 'Can refresh results'))
# 
#     def acknowledge(self, user, days, reason=None, commit=True):
#         # calculate end of requested acknowledgement
#         acknowledged_until = timezone.now() + relativedelta.relativedelta(days=days)
# 
#         # check that we're not accidentally overriding the current setup
#         if self.status in (self.STATUS.warning, self.STATUS.critical):
#             if self.is_acknowledged() and self.acknowledged_until > acknowledged_until:
#                 raise AlreadyAcknowledged()
#         self.acknowledged_at = timezone.now()
#         self.acknowledged_by = user
#         self.acknowledged_until = acknowledged_until
#         self.acknowledged_reason = reason or ''
#         if commit:
#             self.save(update_fields=['acknowledged_at', 'acknowledged_by', 'acknowledged_until', 'acknowledged_reason'])
# 
#     def is_acknowledged(self):
#         return self.acknowledged_until and self.acknowledged_until >= timezone.now()
# 
#     def __str__(self):
#         return self.slug
# 
#     def get_check_instance(self):
#         return datawatch.get_check_class(self.slug)()
# 
#     def get_payload(self):
#         return self.get_check_instance().get_payload(self.identifier)
# 
#     def get_formatted_data(self):
#         return datawatch.get_check_class(self.slug)().format_result_data(self)
# 
#     def latest_status(self, status):
#         return self.status_history.filter(to_status=status).order_by('-created').first()
# 
#     @cached_property
#     def latest_unknown(self):
#         return self.latest_status(self.STATUS.unknown)
# 
#     @cached_property
#     def latest_ok(self):
#         return self.latest_status(self.STATUS.ok)
# 
#     @cached_property
#     def latest_warning(self):
#         return self.latest_status(self.STATUS.warning)
# 
#     @cached_property
#     def latest_critical(self):
#         return self.latest_status(self.STATUS.critical)
# 
# Path: django_datawatch/datawatch.py
# class DatawatchHandler(object):
# class Scheduler(object):
#     def __init__(self):
#     def autodiscover_checks(self, module_name='checks'):
#     def register(self, check_class):
#     def get_all_registered_checks(self):
#     def get_all_registered_check_slugs(self):
#     def get_check_class(self, slug):
#     def get_checks_for_related_model(self, model):
#     def get_checks_for_model(self, model):
#     def get_slug(self, module, class_name):
#     def get_backend(self):
#     def delete_results(self, sender, instance):
#     def update_related(self, sender, instance):
#     def run_checks(self, force=False, slug=None):
#     def get_last_executions(self):
# def make_model_uid(model):
# def delete_results(sender, instance, using, **kwargs):
# def run_checks(sender, instance, created, raw, using, **kwargs):


# Path: django_datawatch/backends/synchronous.py
import logging
from django.core.exceptions import ObjectDoesNotExist
from django_datawatch.backends.base import BaseBackend
from django_datawatch.models import Result
from django_datawatch.datawatch import datawatch

# -*- coding: UTF-8 -*-



logger = logging.getLogger(__name__)


class Backend(BaseBackend):
    def enqueue(self, slug, run_async=True):
        check = self._get_check_instance(slug)
        if not check:
            return

        try:
            for payload in check.generate():
                if payload is None:
                    continue
                datawatch.get_backend().run(check.slug, check.get_identifier(payload))
        except NotImplementedError as e:
            logger.error(e)

    def refresh(self, slug, run_async=True):

        for result in Result.objects.filter(slug=slug):