"""
Contains rich-text related classes.
"""
import re

from django.utils.html import escape

from wagtail.wagtailcore import hooks
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.rich_text import EMBED_HANDLERS
from wagtail.wagtailcore.whitelist import Whitelister
from wagtail.wagtaildocs.models import Document
from wagtailplus.wagtaillinks.models import Link


def expand_db_attributes_for_model(model, attrs, for_editor):
    """
    Given a dictionary of attributes from the <a> tag, return
    the real HTML representation.

    :param model: the model class.
    :param attrs: dictionary of database attributes.
    :param for_editor: flag to display in editor or frontend.
    :rtype: str.
    """
    editor_attrs = ''

    try:
        obj = model.objects.get(id=attrs['id'])

        if for_editor:
            link_type       = model._meta.model.__name__.lower()
            editor_attrs    = 'data-linktype="{0}" data-id="{1}"'
            editor_attrs    = editor_attrs.format(link_type, obj.id)

        # Include title attribute for 508 compliance.
        return '<a {0} href="{1}" title="{2}">'.format(
            editor_attrs,
            escape(obj.url),
            obj.title
        )
    except model.DoesNotExist:
        return '<a>'

class BetterHandler(object):
    """
    Base handler class for embedded links to instances.
    """
    @staticmethod
    def get_db_attributes(tag):
        """
        Given an <a> tag that we've identified as a link embed, return a
        dictionary of the attributes we should have on the resulting
        <a> element.
        """
        return {'id': tag['data-id']}

    @classmethod
    def expand_db_attributes(cls, attrs, for_editor):