from plone import api
from plone.protect.interfaces import IDisableCSRFProtection
from ploneintranet.news.behaviors import INewsSyndication
from Products.Five import BrowserView
from zope.interface import alsoProvides

import logging

log = logging.getLogger(__name__)


def obj2dict(obj, *keys, **keyvalues):
    _dict = dict(obj=obj)
    for k in keys:
        attr = getattr(obj, k)
        if callable(attr):
            # e.g. absolute_url
            _dict[k] = attr()
        else:
            _dict[k] = attr
    for key, value in keyvalues.items():
        _dict[key] = value
    _dict["obj"] = obj
    return _dict


class FeedAggregator(BrowserView):
    def __call__(self):
        alsoProvides(self.request, IDisableCSRFProtection)
        pc = api.portal.get_tool("portal_catalog")
        syndicators = pc.searchResults(portal_type="ploneintranet.news.syndication")
        for brain in syndicators:
            section = brain.getObject()
            syndication = INewsSyndication(section)
            try:
                syndication.sync_news()
            except api.exc.InvalidParameterError:
                user = api.user.get_current()
                log.error(
                    "Ensure that your user ({}) has the "
                    "necessary permission".format(user)
                )
        return "Done"
