# Path: django_datawatch/querysets.py
# class CheckExecutionQuerySet(models.QuerySet):
#     def ghost_executions(self):
#         """
#         :return: check executions that do not have checks anymore (check has been deleted)
#         """
#         return self.exclude(slug__in=datawatch.get_all_registered_check_slugs())
# 
# 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/querysets.py
# class ResultQuerySet(models.QuerySet):
#     def for_user(self, user):
#         return self.filter(Q(assigned_to_group__isnull=True) | Q(assigned_to_group__in=user.groups.all()),
#                            Q(assigned_to_user__isnull=True) | Q(assigned_to_user=user))
# 
#     def failed(self):
#         return self.exclude(status__in=(self.model.STATUS.unknown, self.model.STATUS.ok))
# 
#     def ok(self):
#         return self.filter(status=self.model.STATUS.ok)
# 
#     def unknown(self):
#         return self.filter(status=self.model.STATUS.unknown)
# 
#     def unacknowledged(self):
#         return self.exclude(acknowledged_until__gt=timezone.now())
# 
#     def with_status_name(self):
#         case = Case(output_field=models.CharField())
#         for status_value in self.model.STATUS._db_values:
#             case.cases.append(
#                 When(status=status_value, then=Value(str(self.model.STATUS[status_value]))),
#             )
#         return self.annotate(status_name=case)
# 
#     def get_stats(self):
#         return self.values('status').annotate(amount=Count('id')).with_status_name()
# 
#     def ghost_results(self):
#         """
#         :return: results that do not have checks anymore (check has been deleted)
#         """
#         return self.exclude(slug__in=datawatch.get_all_registered_check_slugs())


from dateutil import relativedelta
from django.utils import timezone
from django.conf import settings
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from django_extensions.db.fields.json import JSONField
from model_utils.choices import Choices
from model_utils.models import TimeStampedModel
from django_datawatch.querysets import CheckExecutionQuerySet
from .datawatch import datawatch
from .querysets import ResultQuerySet

class AlreadyAcknowledged(Exception):
    pass


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)

# Path: django_datawatch/querysets.py
# class CheckExecutionQuerySet(models.QuerySet):
#     def ghost_executions(self):
#         """
#         :return: check executions that do not have checks anymore (check has been deleted)
#         """
#         return self.exclude(slug__in=datawatch.get_all_registered_check_slugs())
# 
# 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/querysets.py
# class ResultQuerySet(models.QuerySet):
#     def for_user(self, user):
#         return self.filter(Q(assigned_to_group__isnull=True) | Q(assigned_to_group__in=user.groups.all()),
#                            Q(assigned_to_user__isnull=True) | Q(assigned_to_user=user))
# 
#     def failed(self):
#         return self.exclude(status__in=(self.model.STATUS.unknown, self.model.STATUS.ok))
# 
#     def ok(self):
#         return self.filter(status=self.model.STATUS.ok)
# 
#     def unknown(self):
#         return self.filter(status=self.model.STATUS.unknown)
# 
#     def unacknowledged(self):
#         return self.exclude(acknowledged_until__gt=timezone.now())
# 
#     def with_status_name(self):
#         case = Case(output_field=models.CharField())
#         for status_value in self.model.STATUS._db_values:
#             case.cases.append(
#                 When(status=status_value, then=Value(str(self.model.STATUS[status_value]))),
#             )
#         return self.annotate(status_name=case)
# 
#     def get_stats(self):
#         return self.values('status').annotate(amount=Count('id')).with_status_name()
# 
#     def ghost_results(self):
#         """
#         :return: results that do not have checks anymore (check has been deleted)
#         """
#         return self.exclude(slug__in=datawatch.get_all_registered_check_slugs())


# Path: django_datawatch/models.py
from dateutil import relativedelta
from django.utils import timezone
from django.conf import settings
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from django_extensions.db.fields.json import JSONField
from model_utils.choices import Choices
from model_utils.models import TimeStampedModel
from django_datawatch.querysets import CheckExecutionQuerySet
from .datawatch import datawatch
from .querysets import ResultQuerySet


class AlreadyAcknowledged(Exception):
    pass


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)