# -*- coding: utf-8 -*-

################################################################
# zopyx.plone.smashdocs
# (C) 2016,  Andreas Jung, www.zopyx.com, Tuebingen, Germany
################################################################

from zope.component import getUtility
from plone.registry.interfaces import IRegistry

from .interfaces import ISmashdocsSettings
from .smashdocument import ISmashDocument

from zopyx.smashdocs import api


def update_metadata(obj, event):
    """ Sync Plone metadata with Smashdocs """

    if ISmashDocument.providedBy(obj):
        return

    try:
        document_id = obj.document_id
    except AttributeError:
        return

    registry = getUtility(IRegistry)
    settings = registry.forInterface(ISmashdocsSettings)

    _safe = lambda x: x or u''

    sd = api.Smashdocs(
        partner_url=settings.partner_url,
        client_id=settings.client_id,
        client_key=settings.client_key,
        group_id=obj.computed_group_id)

    data = dict(
        title=_safe(obj.Title()),
        description=_safe(obj.Description()),
        subtitle=_safe(obj.subtitle),
        footer=_safe(obj.footer),
        tags=obj.Subject())

    sd.update_metadata(obj.document_id, **data)
