from plone import api
from ploneintranet.layout.utils import shorten

try:
    from plone.base.utils import safe_text
except ImportError:
    from Products.CMFPlone.utils import safe_text


def make_description(body_text):
    pt = api.portal.get_tool("portal_transforms")
    stream = pt.convert("html_to_text", body_text)
    data = " ".join(safe_text(stream.getData()).strip().split())
    return shorten(data, length=160, ellipsis="...")


def fix_news_description(obj, event=None):
    """We alway want to have a news description.
    If not provided we will compute it
    """
    obj._teaser = ""
    if not obj.text:
        return
    # Store the auto-generated description so we can later recognize whether the actual
    # description is equal to the auto-generated one
    obj._teaser = make_description(obj.text.output)
    if obj.description:
        return
    obj.description = obj._teaser
