# Path: boardinghouse/contrib/demo/forms.py
# class CreateDemoForm(forms.ModelForm):
#     """Create a new DemoSchema object.
# 
#     Does not allow passing in a user or expiry: those should be set in the view,
#     or use the defaults in the latter case.
#     """
#     class Meta:
#         model = DemoSchema
#         fields = ('from_template',)
# 
# Path: boardinghouse/contrib/demo/models.py
# class DemoSchema(SharedSchemaMixin, models.Model):
#     """A User's demo setup.
# 
#     Each user may only have at most one DemoSchema object, which will have an
#     expiry date.
# 
#     We retain a reference to the template from which it was cloned, so we can
#     easily reset it.
#     """
#     user = models.OneToOneField(settings.AUTH_USER_MODEL,
#                                 on_delete=models.CASCADE,
#                                 primary_key=True,
#                                 related_name='demo_schema')
#     expires_at = models.DateTimeField()
#     from_template = models.ForeignKey('template.SchemaTemplate',
#                                       on_delete=models.CASCADE,
#                                       related_name='demo_schemata',
#                                       limit_choices_to=~models.Q(use_for_demo=None))
# 
#     objects = ExpiringObjectsQuerySet.as_manager()
# 
#     class Meta:
#         verbose_name = 'user demo'
#         verbose_name_plural = 'user demos'
# 
#     def __str__(self):
#         if self.expired:
#             return u'Expired demo for {0} (expired {1} ago)'.format(self.user, timesince(self.expires_at))
# 
#         return u'Demo for {0}: expires at {1} ({2} from now)'.format(
#             self.user, self.expires_at, timeuntil(self.expires_at))
# 
#     @cached_property
#     def schema(self):
#         return '{0}{1}'.format(settings.BOARDINGHOUSE_DEMO_PREFIX, self.user_id)
# 
#     @property
#     def expired(self):
#         return self.expires_at < timezone.now().replace(tzinfo=pytz.utc)
# 
#     @property
#     def name(self):
#         return _('Demo schema ({template_name})').format(template_name=self.from_template.name)
# 
#     @property
#     def _clone(self):
#         return self.from_template.schema
# 
#     def save(self, *args, **kwargs):
#         if not self.expires_at:
#             self.expires_at = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) + settings.BOARDINGHOUSE_DEMO_PERIOD
#         return super(DemoSchema, self).save(*args, **kwargs)
# 
#     def activate(self):
#         if self.expired:
#             raise DemoSchemaExpired()
#         activate_schema(self.schema)
# 
#     def deactivate(self):
#         deactivate_schema()


import json
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from django.views.generic import View
from django.views.generic.edit import DeleteView, BaseCreateView
from .forms import CreateDemoForm
from .models import DemoSchema
    """Create a new Demo for the logged in user.

    Use the provided template, and the default expiry period.
    """
    form_class = CreateDemoForm

    def form_invalid(self, form):
        return HttpResponse(json.dumps({'errors': form.errors}), status=409)

    def form_valid(self, form):
        if DemoSchema.objects.filter(user=self.request.user).exists():
            form.add_error(None, _('Creating a demo when one already exists is not permitted'))
            return self.form_invalid(form)

        form.instance.user = self.request.user
        return super(CreateDemo, self).form_valid(form)


class DeleteDemo(DemoSchemaMixin, DeleteView):
    """Delete the Demo for the logged in user."""


class ResetDemo(DemoSchemaMixin, View):
    """Reset the Demo for the logged in user back to the clean template."""
    def post(self, request, *args, **kwargs):
        # Just use the raw drop/create functions? At this stage, it's simpler (and safer?) to
        # delete the existing DemoSchema object, and create a new one. We reset the demo period,
        # but use the same template.
        demo_schema = self.get_object()
        demo_schema.delete()

# Path: boardinghouse/contrib/demo/forms.py
# class CreateDemoForm(forms.ModelForm):
#     """Create a new DemoSchema object.
# 
#     Does not allow passing in a user or expiry: those should be set in the view,
#     or use the defaults in the latter case.
#     """
#     class Meta:
#         model = DemoSchema
#         fields = ('from_template',)
# 
# Path: boardinghouse/contrib/demo/models.py
# class DemoSchema(SharedSchemaMixin, models.Model):
#     """A User's demo setup.
# 
#     Each user may only have at most one DemoSchema object, which will have an
#     expiry date.
# 
#     We retain a reference to the template from which it was cloned, so we can
#     easily reset it.
#     """
#     user = models.OneToOneField(settings.AUTH_USER_MODEL,
#                                 on_delete=models.CASCADE,
#                                 primary_key=True,
#                                 related_name='demo_schema')
#     expires_at = models.DateTimeField()
#     from_template = models.ForeignKey('template.SchemaTemplate',
#                                       on_delete=models.CASCADE,
#                                       related_name='demo_schemata',
#                                       limit_choices_to=~models.Q(use_for_demo=None))
# 
#     objects = ExpiringObjectsQuerySet.as_manager()
# 
#     class Meta:
#         verbose_name = 'user demo'
#         verbose_name_plural = 'user demos'
# 
#     def __str__(self):
#         if self.expired:
#             return u'Expired demo for {0} (expired {1} ago)'.format(self.user, timesince(self.expires_at))
# 
#         return u'Demo for {0}: expires at {1} ({2} from now)'.format(
#             self.user, self.expires_at, timeuntil(self.expires_at))
# 
#     @cached_property
#     def schema(self):
#         return '{0}{1}'.format(settings.BOARDINGHOUSE_DEMO_PREFIX, self.user_id)
# 
#     @property
#     def expired(self):
#         return self.expires_at < timezone.now().replace(tzinfo=pytz.utc)
# 
#     @property
#     def name(self):
#         return _('Demo schema ({template_name})').format(template_name=self.from_template.name)
# 
#     @property
#     def _clone(self):
#         return self.from_template.schema
# 
#     def save(self, *args, **kwargs):
#         if not self.expires_at:
#             self.expires_at = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) + settings.BOARDINGHOUSE_DEMO_PERIOD
#         return super(DemoSchema, self).save(*args, **kwargs)
# 
#     def activate(self):
#         if self.expired:
#             raise DemoSchemaExpired()
#         activate_schema(self.schema)
# 
#     def deactivate(self):
#         deactivate_schema()


# Path: boardinghouse/contrib/demo/views.py
import json
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from django.views.generic import View
from django.views.generic.edit import DeleteView, BaseCreateView
from .forms import CreateDemoForm
from .models import DemoSchema

    """Create a new Demo for the logged in user.

    Use the provided template, and the default expiry period.
    """
    form_class = CreateDemoForm

    def form_invalid(self, form):
        return HttpResponse(json.dumps({'errors': form.errors}), status=409)

    def form_valid(self, form):
        if DemoSchema.objects.filter(user=self.request.user).exists():
            form.add_error(None, _('Creating a demo when one already exists is not permitted'))
            return self.form_invalid(form)

        form.instance.user = self.request.user
        return super(CreateDemo, self).form_valid(form)


class DeleteDemo(DemoSchemaMixin, DeleteView):
    """Delete the Demo for the logged in user."""


class ResetDemo(DemoSchemaMixin, View):
    """Reset the Demo for the logged in user back to the clean template."""
    def post(self, request, *args, **kwargs):
        # Just use the raw drop/create functions? At this stage, it's simpler (and safer?) to
        # delete the existing DemoSchema object, and create a new one. We reset the demo period,
        # but use the same template.
        demo_schema = self.get_object()
        demo_schema.delete()

        self.object = DemoSchema.objects.create(