from django.conf import settings
from django.core.urlresolvers import reverse_lazy
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from importlib import import_module

from djangoldp.models import Model
from djangoldp_skill.models import Skill

class Address(Model):
    country = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=255, blank=True)

    class Meta(Model.Meta):
        verbose_name_plural = "addresses"
        anonymous_perms = ['view']
        authenticated_perms = ['inherit']
        owner_perms = ['inherit', 'change']
        rdf_type = 'vcard:Address'
        rdf_context = {
            'vcard': "http://www.w3.org/2006/vcard/ns",
            'country': 'vcard:country_name',
            'city': 'vcard:locality'
        }

    def __str__(self):
        if self.country:
            return '{} ({})'.format(self.city, self.country)
        else:
            return self.city

class Contact(Model):
    fullName = models.CharField(max_length=255)
    givenName = models.CharField(max_length=255, blank=True)
    familyName = models.CharField(max_length=255, blank=True)
    email = models.EmailField(max_length=254, blank=True)
    phone = models.CharField(max_length=255, blank=True)
    role = models.CharField(max_length=255, blank=True)

    class Meta(Model.Meta):
        anonymous_perms = ['view']
        authenticated_perms = ['inherit']
        owner_perms = ['inherit', 'change']
        rdf_type = 'vcard:Individual'
        rdf_context = {
            'vcard': "http://www.w3.org/2006/vcard/ns",
            'fullName': 'vcard:fn',
            'givenName': 'vcard:given-name',
            'familyName': 'vcard:family-name',
            'email': 'vcard:hasEmail',
            'phone': 'vcard:hasTelephone',
            'role': 'vcard:role'
        }
    def __str__(self):
        return self.fullName

# allow other modules to add nested fields to Profile
djangoldp_modules = list(settings.DJANGOLDP_PACKAGES)
profile_fields = ['@id', 'user', 'bio', 'slug', 'available', 'job', 'website', 'address', 'skills', 'jabberID', 'name', 'givenName', 'familyName', 'phone']
profile_nested_fields = []
for dldp_module in djangoldp_modules:
    try:
        module_profile_nested_fields = import_module(dldp_module + '.settings').PROFILE_NESTED_FIELDS
        profile_fields += module_profile_nested_fields
        profile_nested_fields += module_profile_nested_fields
    except:
        pass

s_fields = []
s_fields.extend(profile_fields)
s_fields.extend(profile_nested_fields)

class Profile(Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile")
    bio = models.CharField(max_length=2048, blank=True)
    slug = models.SlugField(unique=True, blank=True)
    available = models.NullBooleanField(blank=True)
    job = models.CharField(max_length=150, blank=True)
    website = models.URLField(blank=True)
    address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name="profile", blank=True, null=True)
    skills = models.ManyToManyField(Skill, blank=True)
    jabberID = models.CharField(max_length=255, blank=True, null=True)
    phone = models.CharField(max_length=255, blank=True)

    def get_full_name(self):
        return self.givenName() + " " + self.familyName()

    def name(self):
        return self.get_full_name()

    def givenName(self):
        return self.user.first_name

    def familyName(self):
        return self.user.last_name

    class Meta:
        auto_author = 'user'
        anonymous_perms = ['view']
        authenticated_perms = ['inherit']
        owner_perms = ['inherit', 'change']
        lookup_field = 'slug'
        nested_fields = profile_nested_fields
        serializer_fields = s_fields
        rdf_type = 'foaf:Person'
        rdf_context = {
            'foaf': "http://xmlns.com/foaf/0.1/",
            'vcard': "http://www.w3.org/2006/vcard/ns",
            'schema': "http://schema.org/",
            'user': 'foaf:account',
            'name': 'foaf:name',
            'givenName': 'foaf:givenName',
            'familyName': 'foaf:familyName',
            'picture': 'foaf:depiction',
            'bio': 'bio:biography',
            'phone': 'foaf:phone',
            'jabberID': 'foaf:jabberID',
            'website': 'foaf:homepage',
            'address': 'vcard:hasAddress',
            'skills': 'schema:knowsAbout',
        }

    def __str__(self):
        return '{} ({})'.format(self.get_full_name(), self.user.username)

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        profile = Profile.objects.create(user=instance, slug=instance.username)
        if not Model.is_external(instance) and settings.JABBER_DEFAULT_HOST:
            profile.jabberID = '{}@{}'.format(instance.username, settings.JABBER_DEFAULT_HOST)
            profile.save()
    else:
        try:
            instance.profile.slug = instance.username
            instance.profile.save()
        except:
            pass