# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import

from django.db import models
from django.dispatch import receiver
from django.contrib.sites.models import Site

import multisitesutils

from .managers import SiteManager, SingletonSiteManager


class SiteModel(models.Model):

    """ Abstract model to store the site for dealing with multi sites """

    site = models.ForeignKey(Site)

    objects = models.Manager()
    site_objects = SiteManager()

    class Meta:
        abstract = True

    def save(self, *args, **kws):
        # setup a default site ONLY IF there is no site
        try:
            self.site
        except:
            self.site = Site.objects.get_current()
        super(SiteModel, self).save(*args, **kws)

    def save_keeping_site(self, *args, **kws):
        # TODO: find out a better way of do this
        super(SiteModel, self).save(*args, **kws)


class Preferences(models.Model):
    """ Abstract model for Site Preferences. see the below doc. """
    site = models.ForeignKey(Site)

    objects = models.Manager()
    singleton = SingletonSiteManager()

    class Meta:
        abstract = True

    def save(self, *args, **kws):
        if not self.pk:
            try:
                self.site
            except:
                self.site = Site.objects.get_current()
        super(Preferences, self).save(*args, **kws)


@receiver(models.signals.class_prepared)
def preferences_class_prepared(sender, *args, **kwargs):
    """
    Adds preferences dynamically to multisitesutils.preferences,
    thus enabling easy access from code like this:

    # Getting a value preference
    >>> from multisitesutils import preferences
    >>> field_one = preferences.MyCustomPreferences.field_one

    # Saving a new value
    >>> my_custom_pref = MyCustomPreferences.singleton.get()
    >>> my_custom_pref.field_one = 'updated'
    >>> my_custom_pref.save()

    For a given model preferences:

    class MyCustomPreferences(Preferences):
        field_one = models.CharField(...)
        field_two = models.CharField(...)

    """
    cls = sender
    if issubclass(cls, Preferences):
        cls.add_to_class('singleton', SingletonSiteManager())
        setattr(multisitesutils.Preferences, cls._meta.object_name,
                property(lambda x: cls.singleton.get()))
