# Path: domainchecks/forms.py
# class CheckResultFilter(django_filters.FilterSet):
#     """Filter check results for a time range."""
# 
#     start = django_filters.DateTimeFilter(
#         name='checked_on', lookup_type='gte', required=True)
#     end = django_filters.DateTimeFilter(
#         name='checked_on', lookup_type='lte', required=True)
# 
#     class Meta:
#         model = models.CheckResult
#         form = CheckFilterForm
#         order_by = ('-checked_on', )
# 
# class DomainForm(forms.ModelForm):
#     """Form to allow users to create/edit their own domains."""
# 
#     class Meta:
#         model = models.Domain
#         fields = ('name', )
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self.checks = DomainCheckFormSet(
#             instance=self.instance, prefix='checks',
#             data=self.data if self.is_bound else None)
# 
#     def is_valid(self):
#         domain_valid = super().is_valid()
#         checks_valid = self.checks.is_valid()
#         return domain_valid and checks_valid
# 
#     def save(self, commit=True):
#         domain = super().save(commit=commit)
#         domain._checks = self.checks.save(commit=commit)
#         return domain
# 
# Path: domainchecks/models.py
# class Domain(models.Model):
#     """Domain managed by a user."""
# 
#     name = models.CharField(max_length=253, unique=True)
#     owner = models.ForeignKey(settings.AUTH_USER_MODEL)
# 
#     def __str__(self):
#         return self.name
# 
#     def get_absolute_url(self):
#         return reverse('status-detail', kwargs={'domain': self.name})
# 
# class DomainCheck(models.Model):
#     """Configured website check."""
# 
#     PROTOCOL_HTTP = 'http'
#     PROTOCOL_HTTPS = 'https'
# 
#     PROTOCOL_CHOICES = (
#         (PROTOCOL_HTTP, 'HTTP'),
#         (PROTOCOL_HTTPS, 'HTTPS'),
#     )
# 
#     METHOD_GET = 'get'
#     METHOD_POST = 'post'
#     METHOD_PUT = 'put'
#     METHOD_DELETE = 'delete'
#     METHOD_HEAD = 'head'
# 
#     METHOD_CHOICES = (
#         (METHOD_GET, 'GET'),
#         (METHOD_POST, 'POST'),
#         (METHOD_PUT, 'PUT'),
#         (METHOD_DELETE, 'DELETE'),
#         (METHOD_HEAD, 'HEAD'),
#     )
# 
#     domain = models.ForeignKey(Domain)
#     path = models.CharField(max_length=1024)
#     protocol = models.CharField(
#         max_length=5, choices=PROTOCOL_CHOICES, default=PROTOCOL_HTTP)
#     method = models.CharField(
#         max_length=6, choices=METHOD_CHOICES, default=METHOD_GET)
#     is_active = models.BooleanField(default=True)
# 
#     objects = DomainCheckQuerySet.as_manager()
# 
#     def __str__(self):
#         return '{method} {url}'.format(
#             method=self.get_method_display(), url=self.url)
# 
#     @property
#     def url(self):
#         return '{protocol}://{domain}{path}'.format(
#             protocol=self.protocol, domain=self.domain, path=self.path)
# 
#     def run_check(self, timeout=10):
#         start = time.time()
#         result = CheckResult(domain_check=self, checked_on=now())
#         try:
#             response = requests.request(
#                 self.method, self.url, allow_redirects=False, timeout=timeout)
#             result.status_code = response.status_code
#             response.raise_for_status()
#         except requests.exceptions.ConnectionError:
#             # Host could not be resolved or the connection was refused
#             pass
#         except requests.exceptions.Timeout:
#             # Request timed out
#             pass
#         except requests.exceptions.RequestException:
#             # Server responded with 4XX or 5XX status code
#             result.response_body = response.text
#         else:
#             result.response_body = response.text
#         finally:
#             result.response_time = time.time() - start
#             result.save()
# 
# class CheckResult(models.Model):
#     """Result of a status check on a website."""
# 
#     domain_check = models.ForeignKey(DomainCheck)
#     checked_on = models.DateTimeField()
#     status_code = models.PositiveIntegerField(null=True)
#     response_time = models.FloatField(null=True)
#     response_body = models.TextField(default='')


from django.core.exceptions import PermissionDenied
from django.http import JsonResponse
from django.views.generic import CreateView, ListView, UpdateView
from django.shortcuts import get_object_or_404
from .forms import CheckResultFilter, DomainForm
from .models import Domain, DomainCheck, CheckResult



class StatusList(ListView):
    template_name = 'domainchecks/status-list.html'
    context_object_name = 'domains'

    def get_queryset(self):
        if self.request.user.is_authenticated():
            return DomainCheck.objects.active().filter(
                domain__owner=self.request.user
            ).values('domain__name').status().order_by('domain__name')
        else:

# Path: domainchecks/forms.py
# class CheckResultFilter(django_filters.FilterSet):
#     """Filter check results for a time range."""
# 
#     start = django_filters.DateTimeFilter(
#         name='checked_on', lookup_type='gte', required=True)
#     end = django_filters.DateTimeFilter(
#         name='checked_on', lookup_type='lte', required=True)
# 
#     class Meta:
#         model = models.CheckResult
#         form = CheckFilterForm
#         order_by = ('-checked_on', )
# 
# class DomainForm(forms.ModelForm):
#     """Form to allow users to create/edit their own domains."""
# 
#     class Meta:
#         model = models.Domain
#         fields = ('name', )
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self.checks = DomainCheckFormSet(
#             instance=self.instance, prefix='checks',
#             data=self.data if self.is_bound else None)
# 
#     def is_valid(self):
#         domain_valid = super().is_valid()
#         checks_valid = self.checks.is_valid()
#         return domain_valid and checks_valid
# 
#     def save(self, commit=True):
#         domain = super().save(commit=commit)
#         domain._checks = self.checks.save(commit=commit)
#         return domain
# 
# Path: domainchecks/models.py
# class Domain(models.Model):
#     """Domain managed by a user."""
# 
#     name = models.CharField(max_length=253, unique=True)
#     owner = models.ForeignKey(settings.AUTH_USER_MODEL)
# 
#     def __str__(self):
#         return self.name
# 
#     def get_absolute_url(self):
#         return reverse('status-detail', kwargs={'domain': self.name})
# 
# class DomainCheck(models.Model):
#     """Configured website check."""
# 
#     PROTOCOL_HTTP = 'http'
#     PROTOCOL_HTTPS = 'https'
# 
#     PROTOCOL_CHOICES = (
#         (PROTOCOL_HTTP, 'HTTP'),
#         (PROTOCOL_HTTPS, 'HTTPS'),
#     )
# 
#     METHOD_GET = 'get'
#     METHOD_POST = 'post'
#     METHOD_PUT = 'put'
#     METHOD_DELETE = 'delete'
#     METHOD_HEAD = 'head'
# 
#     METHOD_CHOICES = (
#         (METHOD_GET, 'GET'),
#         (METHOD_POST, 'POST'),
#         (METHOD_PUT, 'PUT'),
#         (METHOD_DELETE, 'DELETE'),
#         (METHOD_HEAD, 'HEAD'),
#     )
# 
#     domain = models.ForeignKey(Domain)
#     path = models.CharField(max_length=1024)
#     protocol = models.CharField(
#         max_length=5, choices=PROTOCOL_CHOICES, default=PROTOCOL_HTTP)
#     method = models.CharField(
#         max_length=6, choices=METHOD_CHOICES, default=METHOD_GET)
#     is_active = models.BooleanField(default=True)
# 
#     objects = DomainCheckQuerySet.as_manager()
# 
#     def __str__(self):
#         return '{method} {url}'.format(
#             method=self.get_method_display(), url=self.url)
# 
#     @property
#     def url(self):
#         return '{protocol}://{domain}{path}'.format(
#             protocol=self.protocol, domain=self.domain, path=self.path)
# 
#     def run_check(self, timeout=10):
#         start = time.time()
#         result = CheckResult(domain_check=self, checked_on=now())
#         try:
#             response = requests.request(
#                 self.method, self.url, allow_redirects=False, timeout=timeout)
#             result.status_code = response.status_code
#             response.raise_for_status()
#         except requests.exceptions.ConnectionError:
#             # Host could not be resolved or the connection was refused
#             pass
#         except requests.exceptions.Timeout:
#             # Request timed out
#             pass
#         except requests.exceptions.RequestException:
#             # Server responded with 4XX or 5XX status code
#             result.response_body = response.text
#         else:
#             result.response_body = response.text
#         finally:
#             result.response_time = time.time() - start
#             result.save()
# 
# class CheckResult(models.Model):
#     """Result of a status check on a website."""
# 
#     domain_check = models.ForeignKey(DomainCheck)
#     checked_on = models.DateTimeField()
#     status_code = models.PositiveIntegerField(null=True)
#     response_time = models.FloatField(null=True)
#     response_body = models.TextField(default='')


# Path: domainchecks/views.py
from django.core.exceptions import PermissionDenied
from django.http import JsonResponse
from django.views.generic import CreateView, ListView, UpdateView
from django.shortcuts import get_object_or_404
from .forms import CheckResultFilter, DomainForm
from .models import Domain, DomainCheck, CheckResult




class StatusList(ListView):
    template_name = 'domainchecks/status-list.html'
    context_object_name = 'domains'

    def get_queryset(self):
        if self.request.user.is_authenticated():
            return DomainCheck.objects.active().filter(
                domain__owner=self.request.user
            ).values('domain__name').status().order_by('domain__name')
        else:

            return DomainCheck.objects.none()