# Path: coffeestats/caffeine/models.py
# ACTION_TYPES = Choices((0, "change_email", _("Change email")))
# 
# class Action(models.Model):
#     """
#     Action model.
# 
#     """
# 
#     user = models.ForeignKey("User", models.PROTECT)
#     code = models.CharField(_("action code"), max_length=32, unique=True)
#     created = AutoCreatedField(_("created"))
#     validuntil = models.DateTimeField(_("valid until"), db_index=True)
#     atype = models.PositiveSmallIntegerField(
#         _("action type"), choices=ACTION_TYPES, db_index=True
#     )
#     data = models.TextField(_("action data"))
# 
#     objects = ActionManager()
# 
#     class Meta:
#         ordering = ["-validuntil"]
# 
#     def __str__(self):
#         return "%s valid until %s" % (ACTION_TYPES[self.atype], self.validuntil)
# 
# class Caffeine(models.Model):
#     """
#     Caffeinated drink model.
# 
#     """
# 
#     ctype = models.PositiveSmallIntegerField(choices=DRINK_TYPES, db_index=True)
#     user = models.ForeignKey("User", models.PROTECT, related_name="caffeines")
#     date = models.DateTimeField(_("consumed"), db_index=True)
#     entrytime = AutoCreatedField(_("entered"), db_index=True)
#     timezone = models.CharField(max_length=40, db_index=True, blank=True)
# 
#     objects = CaffeineManager()
# 
#     class Meta:
#         ordering = ["-date"]
# 
#     def clean(self):
#         recent_caffeine = Caffeine.objects.find_recent_caffeine(
#             self.user, self.date, self.ctype
#         )
#         if recent_caffeine:
#             raise ValidationError(
#                 _(
#                     "Your last %(drink)s was less than %(minutes)d minutes "
#                     "ago at %(date)s %(timezone)s"
#                 ),
#                 code="drink_frequency",
#                 params={
#                     "drink": DRINK_TYPES[self.ctype],
#                     "minutes": settings.MINIMUM_DRINK_DISTANCE,
#                     "date": recent_caffeine.date,
#                     "timezone": recent_caffeine.timezone,
#                 },
#             )
#         super(Caffeine, self).clean()
# 
#     def __str__(self):
#         return (
#             "%s at %s %s"
#             % (
#                 DRINK_TYPES[self.ctype],
#                 self.date.strftime(settings.CAFFEINE_DATETIME_FORMAT),
#                 self.timezone or "",
#             )
#         ).strip()
# 
#     def format_type(self):
#         return DRINK_TYPES[self.ctype]
# 
# class User(AbstractUser):
#     """
#     User model.
# 
#     """
# 
#     cryptsum = models.CharField(_("old password hash"), max_length=60, blank=True)
#     location = models.CharField(max_length=128, blank=True)
#     public = models.BooleanField(default=True)
#     token = models.CharField(max_length=32, unique=True)
#     timezone = models.CharField(_("timezone"), max_length=40, db_index=True, blank=True)
# 
#     objects = CaffeineUserManager()
# 
#     def get_absolute_url(self):
#         return reverse("public", kwargs={"username": self.username})
# 
#     def __str__(self):
#         return self.get_full_name() or self.username
# 
#     def export_csv(self):
#         subject = _("Your caffeine records")
#         body = _("Attached is your caffeine track record.")
#         email = EmailMessage(subject, body, to=[self.email])
#         now = timezone.now().strftime(settings.CAFFEINE_DATETIME_FORMAT)
#         for drink in ("coffee", "mate"):
#             email.attachments.append(
#                 (
#                     "%s-%s.csv" % (drink, now),
#                     Caffeine.objects.get_csv_data(getattr(DRINK_TYPES, drink), self),
#                     "text/csv",
#                 )
#             )
#         email.send()
# 
#     def has_usable_password(self):
#         """
#         Checks whether the current user has either an old password hash or a
#         valid new password hash.
# 
#         """
#         return self.cryptsum or super(User, self).has_usable_password()
# 
#     def set_password(self, password):
#         """
#         Sets the password and creates the authentication token if it is not
#         set.
# 
#         """
#         super(User, self).set_password(password)
#         if not self.token:
#             # on the run token
#             # TODO: use something better for API authentication
#             self.token = md5((self.username + password).encode("utf8")).hexdigest()


from datetime import datetime
from django import forms
from django.conf import settings
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django_registration.forms import RegistrationFormUniqueEmail
from .models import (
    ACTION_TYPES,
    Action,
    Caffeine,
    User,
)

        """
        emailuser = User.objects.filter(
            email__iexact=self.cleaned_data['email']).first()
        if emailuser is not None and emailuser != self.instance:
            raise forms.ValidationError(DUPLICATE_EMAIL_ERROR)
        if self.cleaned_data['email'] != self.instance.email:
            self.email_action = Action.objects.create_action(
                self.instance, ACTION_TYPES.change_email,
                self.cleaned_data['email'],
                settings.EMAIL_CHANGE_ACTION_VALIDITY)
            self.cleaned_data['email'] = self.instance.email
        return self.cleaned_data['email']

    def clean(self):
        cleaned_data = super(SettingsForm, self).clean()
        if 'password2' in self.cleaned_data and \
                self.cleaned_data['password2']:
            self.password_set = True
            self.instance.set_password(
                self.cleaned_data['password2'])
        return cleaned_data


class SelectTimeZoneForm(forms.ModelForm):
    """
    This is the form for selecting a user's time zone.

    """
    class Meta:

# Path: coffeestats/caffeine/models.py
# ACTION_TYPES = Choices((0, "change_email", _("Change email")))
# 
# class Action(models.Model):
#     """
#     Action model.
# 
#     """
# 
#     user = models.ForeignKey("User", models.PROTECT)
#     code = models.CharField(_("action code"), max_length=32, unique=True)
#     created = AutoCreatedField(_("created"))
#     validuntil = models.DateTimeField(_("valid until"), db_index=True)
#     atype = models.PositiveSmallIntegerField(
#         _("action type"), choices=ACTION_TYPES, db_index=True
#     )
#     data = models.TextField(_("action data"))
# 
#     objects = ActionManager()
# 
#     class Meta:
#         ordering = ["-validuntil"]
# 
#     def __str__(self):
#         return "%s valid until %s" % (ACTION_TYPES[self.atype], self.validuntil)
# 
# class Caffeine(models.Model):
#     """
#     Caffeinated drink model.
# 
#     """
# 
#     ctype = models.PositiveSmallIntegerField(choices=DRINK_TYPES, db_index=True)
#     user = models.ForeignKey("User", models.PROTECT, related_name="caffeines")
#     date = models.DateTimeField(_("consumed"), db_index=True)
#     entrytime = AutoCreatedField(_("entered"), db_index=True)
#     timezone = models.CharField(max_length=40, db_index=True, blank=True)
# 
#     objects = CaffeineManager()
# 
#     class Meta:
#         ordering = ["-date"]
# 
#     def clean(self):
#         recent_caffeine = Caffeine.objects.find_recent_caffeine(
#             self.user, self.date, self.ctype
#         )
#         if recent_caffeine:
#             raise ValidationError(
#                 _(
#                     "Your last %(drink)s was less than %(minutes)d minutes "
#                     "ago at %(date)s %(timezone)s"
#                 ),
#                 code="drink_frequency",
#                 params={
#                     "drink": DRINK_TYPES[self.ctype],
#                     "minutes": settings.MINIMUM_DRINK_DISTANCE,
#                     "date": recent_caffeine.date,
#                     "timezone": recent_caffeine.timezone,
#                 },
#             )
#         super(Caffeine, self).clean()
# 
#     def __str__(self):
#         return (
#             "%s at %s %s"
#             % (
#                 DRINK_TYPES[self.ctype],
#                 self.date.strftime(settings.CAFFEINE_DATETIME_FORMAT),
#                 self.timezone or "",
#             )
#         ).strip()
# 
#     def format_type(self):
#         return DRINK_TYPES[self.ctype]
# 
# class User(AbstractUser):
#     """
#     User model.
# 
#     """
# 
#     cryptsum = models.CharField(_("old password hash"), max_length=60, blank=True)
#     location = models.CharField(max_length=128, blank=True)
#     public = models.BooleanField(default=True)
#     token = models.CharField(max_length=32, unique=True)
#     timezone = models.CharField(_("timezone"), max_length=40, db_index=True, blank=True)
# 
#     objects = CaffeineUserManager()
# 
#     def get_absolute_url(self):
#         return reverse("public", kwargs={"username": self.username})
# 
#     def __str__(self):
#         return self.get_full_name() or self.username
# 
#     def export_csv(self):
#         subject = _("Your caffeine records")
#         body = _("Attached is your caffeine track record.")
#         email = EmailMessage(subject, body, to=[self.email])
#         now = timezone.now().strftime(settings.CAFFEINE_DATETIME_FORMAT)
#         for drink in ("coffee", "mate"):
#             email.attachments.append(
#                 (
#                     "%s-%s.csv" % (drink, now),
#                     Caffeine.objects.get_csv_data(getattr(DRINK_TYPES, drink), self),
#                     "text/csv",
#                 )
#             )
#         email.send()
# 
#     def has_usable_password(self):
#         """
#         Checks whether the current user has either an old password hash or a
#         valid new password hash.
# 
#         """
#         return self.cryptsum or super(User, self).has_usable_password()
# 
#     def set_password(self, password):
#         """
#         Sets the password and creates the authentication token if it is not
#         set.
# 
#         """
#         super(User, self).set_password(password)
#         if not self.token:
#             # on the run token
#             # TODO: use something better for API authentication
#             self.token = md5((self.username + password).encode("utf8")).hexdigest()


# Path: coffeestats/caffeine/forms.py
from datetime import datetime
from django import forms
from django.conf import settings
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django_registration.forms import RegistrationFormUniqueEmail
from .models import (
    ACTION_TYPES,
    Action,
    Caffeine,
    User,
)


        """
        emailuser = User.objects.filter(
            email__iexact=self.cleaned_data['email']).first()
        if emailuser is not None and emailuser != self.instance:
            raise forms.ValidationError(DUPLICATE_EMAIL_ERROR)
        if self.cleaned_data['email'] != self.instance.email:
            self.email_action = Action.objects.create_action(
                self.instance, ACTION_TYPES.change_email,
                self.cleaned_data['email'],
                settings.EMAIL_CHANGE_ACTION_VALIDITY)
            self.cleaned_data['email'] = self.instance.email
        return self.cleaned_data['email']

    def clean(self):
        cleaned_data = super(SettingsForm, self).clean()
        if 'password2' in self.cleaned_data and \
                self.cleaned_data['password2']:
            self.password_set = True
            self.instance.set_password(
                self.cleaned_data['password2'])
        return cleaned_data


class SelectTimeZoneForm(forms.ModelForm):
    """
    This is the form for selecting a user's time zone.

    """
    class Meta:

        model = User