# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django.core.cache import cache
from django.utils.translation import ugettext_lazy as _


class Setting(models.Model):
    """
    Site administration settings
    """
    app = models.CharField(_(u'application'), max_length=70,
                           choices=((app.rsplit('.', 1)[1], app.rsplit('.', 1)[1]) for app in settings.INSTALLED_APPS if
                                    app.startswith('{{ project_name }}')), null=True, blank=True)
    key = models.CharField(_(u'key'), max_length=70)
    value = models.TextField(_(u'value'))
    comment = models.TextField(_(u'comment'))

    def save(self, *args, **kwargs):
        result = super(Setting, self).save(*args, **kwargs)
        cache_key = '{app}.{key}'.format(app=self.app, key=self.key)
        # update cache
        cache.set(cache_key, self.value, None)
        return result

    def __unicode__(self):
        return self.comment

    class Meta:
        verbose_name = _(u'setting')
        verbose_name_plural = _(u'settings')
        unique_together = ('app', 'key')


def usersetting(app, key, default_value=None):
    """
    Get user defined setting value
    """
    cache_key = '{app}.{key}'.format(app=app, key=key)
    cached_value = cache.get(cache_key)
    if cached_value is None:
        try:
            cached_value = Setting.objects.get(app=app, key=key).value
        except Setting.DoesNotExist:
            cached_value = default_value
        # cache forever
        cache.set(cache_key, cached_value, None)
    return cached_value
