from django.db import models
from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser
from django.core.validators import RequiredIfOtherFieldEquals
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
from templatetags import features
import types, re

STATUS_CHOICES = [
    "Open",
    "Closed",
    "Closed Before",
    "Closed After"]

DEFAULT_MESSAGE = """Sorry, this service is unavailable at this time."""

class Feature(models.Model):
    name   = models.SlugField(unique=True)
    status = models.PositiveIntegerField(default=0,
        choices=(tuple(enumerate(STATUS_CHOICES))))
    allow_staff     = models.BooleanField(default=True,
        help_text=("If True, then users with staff access will be allowed to "
                   "access the site feature."))
    allow_superuser = models.BooleanField(default=True,
        help_text=("If True, then users with superuser access will be allowed "
                   "to access the site feature."))
    datetime = models.DateTimeField(blank=True, null=True,
        validator_list=[RequiredIfOtherFieldEquals('status', '2',("A datetime "
                            "must be specified if status is 'Closed Before'.")),
                        RequiredIfOtherFieldEquals('status', '3',("A datetime "
                            "must be specified if status is 'Closed After'."))],
        help_text=("Required if status is set to 'Closed Before' or 'Closed After'."))
    message = models.TextField(default=DEFAULT_MESSAGE,
        help_text=("This field, if using the default template, supports "
                   "full django markup. This Feature will be in the context "
                   "variable 'feature'. RequestContext is used."))
    
    class Admin:
        list_display  = ('name', 'status', 'datetime',
                         'allow_staff', 'allow_superuser', 'is_enabled')
        date_hierarchy = 'datetime'
        list_filter   = ('status', 'datetime')
        search_fields = ('name', 'message')
    
    def __unicode__(self):
        res = unicode(self.name + u": " + STATUS_CHOICES[int(self.status)])
        if int(self.status) > 1 and self.datetime is not None:
            res += u": " + unicode(self.datetime.strftime("%c"))
        return res
    
    @property
    def is_enabled(self):
        if self.status == 0: return True
        now = datetime.now()
        if self.status == 2 and now > self.datetime: return True
        if self.status == 3 and now < self.datetime: return True
        return False
    
    @property
    def is_disabled(self):
        return not self.is_enabled

features.Feature = Feature
