from django.db.models import TextField
from django.utils.html import escape
from django.forms import LargeTextField
from django.core import validators
from django.conf import settings

# Monkeypatch to tell Django which SQL datatype to use.  If we ever use a
# different DBMS, we'll have to do this for the relevant backend!
from django.db.backends.mysql import creation
creation.DATA_TYPES['MCETextField'] = 'longtext'


class MCELargeTextField(LargeTextField):

    # Some obscure CSS issue is preventing me from just implementing this as an
    # empty subclass -- that should work, since LargeTextField's textarea's
    # class HTML-attribute includes the Field class' name.  When I do that, I
    # get a funny-looking editor.  I guess we need the Django LargeTextField
    # CSS for some reason.
##     pass

    def __init__(self, *args, **kwds):
        LargeTextField.__init__(self, *args, **kwds)
        self.validator_list.append(isValidTinyMceXhtmlFragment)

    def render(self, data):
        if data is None:
            data = ''
        if isinstance(data, unicode):
            data = data.encode(settings.DEFAULT_CHARSET)
        return '<textarea id="%s" class="vLargeTextField%s mceEditor" name="%s" rows="%s" cols="%s">%s</textarea>' % \
            (self.get_id(), self.is_required and ' required' or '',
            self.field_name, self.rows, self.cols, escape(data))


class MCETextField(TextField):
    def get_manipulator_field_objs(self):
        return [MCELargeTextField]


def isValidTinyMceXhtmlFragment(field_data, all_data):
    # Strictly, this doesn't check for a proper XHTML frament (e.g. may be
    # missing <p> tags if the content is really short): MCETextField just
    # stores whatever TinyMCE gives us, and we fix it up to give a XHTML
    # document with xhtmlDocFromTinymceXhtmlFragment().  The field data must
    # also be valid UTF-8, since xhtmlDocFromTinymceXhtmlFragment declares that
    # it is.
    import pyRXPU
    from rlextra.radxml.xmlutils import validateXhtmlDocument
    from rldjango.common.transform import xhtmlDocFromTinymceXhtmlFragment
    doc = xhtmlDocFromTinymceXhtmlFragment(field_data, addMissingPTag=True)
    try:
        validateXhtmlDocument(doc)
    except pyRXPU.error, exc:
        raise validators.ValidationError(str(exc))
