from weakref import WeakKeyDictionary, WeakValueDictionary

from twisted.cred.portal import IRealm


_providerCache = WeakKeyDictionary()

def getServiceProvider(store, iface):
    """
    Retrieve the provider of a particular service interface.

    The interface is located as a powerup in the application store.

    @param store: The site store, or any substore thereof

    @param iface: The service interface required
    """
    siteStore = store
    while siteStore.parent:
        siteStore = siteStore.parent

    _ifaceCache = _providerCache.setdefault(siteStore, WeakValueDictionary())
    provider = _ifaceCache.get(iface)
    if provider is None:
        ls = IRealm(siteStore)
        la = ls.accountByAddress(u'FlyingCircus', None)
        provider = iface(la)
        _ifaceCache[iface] = provider

    return provider
