from django import forms
from django.forms import fields
from django.db import models
from django.db.models import permalink
from django.conf import settings
import re, datetime

from couchdbkit.ext.django.schema import *
from couchdbkit.ext.django.forms import *
from couchdbkit.exceptions import ResourceNotFound

from django.utils.translation import gettext_lazy as _

MARKUP_LANGUAGE = getattr(settings, 'MARKUP_LANGUAGE', None)

def markup(text, small_headings=False, no_follow=True, escape=False,
           scale_headings=True):
    """Markup text using the markup language specified in the settings.
    """
    if MARKUP_LANGUAGE == 'markdown':
        import markdown
        safe_mode = 'escape' if escape else None
        try:
            import pygments
            options = ['codehilite', 'extra', 'toc']
            if scale_headings:
                options.append('headerid(level=3, forceid=False)')
            text = markdown.markdown(text, options, safe_mode=safe_mode)

        except ImportError:
            options = ['extra', 'toc']
            if scale_headings:
                options.append('headerid(level=3, forceid=False)')
            text = markdown.markdown(text, options, safe_mode=safe_mode)

    if small_headings:
        text = re.sub('<(/?h)[1-6]', '<\g<1>5', text)

    if no_follow:
        text = re.sub('<a (?![^>]*nofollow)', '<a rel="nofollow" ', text)

    return text

class MailArchive(Document):
    head_to = StringProperty()
    head_from = StringProperty()
    head_subject = StringProperty()
    head_date = StringProperty()
    message_id = StringProperty()
    header = StringProperty()
    body = StringProperty()
    body_text = StringProperty()
    body_html = StringProperty()
    flag = StringProperty()
    publish_date = DateTimeProperty(required=True, default=datetime.datetime.now)
    is_admin = BooleanProperty(required=True, default=True)    
    is_superuser = BooleanProperty(required=True, default=True)
    # _attachments = ListProperty(required=False, default=None)

    def save(self):
        super(MailArchive, self).save()

    def save_docs(self):
        super(MailArchive, self).save_docs()

    def delete(self):
        super(MailArchive, self).delete()

    class Meta:
        ordering = ['publish_date']
        app_label = "mailreactor"

    def __unicode__(self):
        return self.header

    def _get_id(self):
        return self._id

    id = property(_get_id)

    @classmethod
    def get_email(self, id):
        param = {"key": id}      
        design = MailArchive._meta.app_label
        r = MailArchive.view('%s/%s-email_by_id' % (design, design),
                     include_docs=True,
                     **param).first()
        if r:
            return r
        return None 

    @classmethod
    def all_mails(self, limit=10000000000, descending=True, reduce=True):
        param = {"limit": limit}
        design = MailArchive._meta.app_label
        r = MailArchive.view('%s/%s-all' % (design, design),
                include_docs=True,
                descending=True,
                reduce=False,
                limit=limit
            )
        if r:
            return r.iterator()
        return None

    @classmethod
    def count(self):
        design = MailArchive._meta.app_label
        r = MailArchive.view('%s/%s-all' % (design, design),
                reduce=True,
            )
        if r:
            return r.first()['value']
        return '0'