from django.contrib.gis.db import models
from django.utils.safestring import mark_safe
from django.contrib.contenttypes.models import ContentType
from markdown import markdown
import re
from django.core.exceptions import ObjectDoesNotExist  
        
class ChronokiwiBaseObject(models.Model):
    slug = models.SlugField(max_length=80, unique=True)
    name = models.CharField(max_length=80)
    description = models.TextField()
    lastUpdate=models.DateTimeField(auto_now=True)
    picture = models.ImageField(upload_to='events', null=True)
    geometry = models.MultiPolygonField()
    objects = models.GeoManager()
    descriptionAuthor = models.CharField(max_length=80, default='devnewton')
    descriptionLicense = models.CharField(max_length=80, default='CC-BY-SA')
    pictureAuthor = models.CharField(max_length=80, default='voir les metadata')
    pictureLicense = models.CharField(max_length=80, default='voir les metadata')
    def description_to_html(self):
        def replace_link(link):
            slug = link.group('slug')
            try:
                event = ChronokiwiEvent.objects.get(slug__exact=slug)
                return u'(%s)' % event.get_absolute_url()
            except ObjectDoesNotExist:
                try:
                    chronology = ChronokiwiChronology.objects.get(slug__exact=slug)
                    return u'(%s)' % chronology.get_absolute_url()
                except ObjectDoesNotExist:
                    return u'(%s)' % slug

        description_preparsed = re.sub(r'\(\((?P<slug>[\_\w-]+)\)\)', replace_link, self.description)
        description_parsed = markdown(description_preparsed)
        return description_parsed
    class Meta:
        abstract = True

class ChronokiwiEvent(ChronokiwiBaseObject):
    date = models.DateField()
    def __unicode__(self):
        return self.name
    @models.permalink
    def get_absolute_url(self):
        return ('events.views.event_detail', [str(self.id)])

class ChronokiwiChronology(ChronokiwiBaseObject):
    events = models.ManyToManyField(ChronokiwiEvent, related_name='chronologies')
    def __unicode__(self):
        return self.name
    @models.permalink
    def get_absolute_url(self):
        return ('events.views.chronology_detail', [str(self.id)])
    def sorted_events(self):
        return self.events.all().order_by("-date")