/*
 *  TnCachingNetworkResourceProxy.h
 *  Map Rendering Engine Proxy Common
 *
 *  Created by Thant on 03/25/2013
 *  Copyright 2013 TeleNav Inc. All rights reserved.
 *
 */

#ifndef TN_CACHING_NETWORK_RESOURCE_PROXY_H
#define TN_CACHING_NETWORK_RESOURCE_PROXY_H

#include <map>
#include <foundation/TnTypes.h>
#include <RenderEngine/ITnMapResourceProxy.h>
#include <GenericProxy/TnNetworkResourceProxy.h>
#include <GenericProxy/TnCache.h>


class TnCachingNetworkResourceProxy : public ITnMapResourceProxy
{
public:

    typedef Tn::Foundation::shared_ptr<TnCachingNetworkResourceProxy> ptr;

    /*  This has its own thread pool for cache fetching. It also
     *  passes threadCount to the TnNetworkResourceProxy, which has
     *  its own thread pool.
     */

    static ptr Create(uint32_t threadCount);

    virtual ~TnCachingNetworkResourceProxy();

    void AddCache(TnCache::ptr const & cache);
    bool RemoveCache(std::string const & cacheName); // returns true upon success


    // TnNetworkResourceProxy supports prefetch

    virtual bool PrefetchSupported(std::string const & cacheName) const;
    virtual void RequestResourcePrefetch(std::string const & url, std::string const & cacheName, uint32_t priority);

    // ITnMapResourceProxy
    virtual bool RequestResourceSynchronously(ITnMapResourceData::ptr const & data);
    virtual void RequestResource(ITnMapResourceData::ptr const & data, uint32_t priority);
    virtual void CancelRequest(ITnMapResourceData::ptr const & data);

    virtual void EnableHttpProxy(const std::string & url, 
                                 int port, 
                                 const std::string & name = "", 
                                 const std::string & password = "");
    virtual void DisableHttpProxy();

private:

    TnCachingNetworkResourceProxy(uint32_t threadCount);

    void LoadFromCache(ITnMapResourceData::ptr const &, TnCache::ptr const &);
    void LoadFromNetwork(ITnMapResourceData::ptr const &);

    // Background threads
    boost::threadpool::prio_pool m_threadpool;

    TnNetworkResourceProxy::ptr m_networkResourceProxy;

    typedef std::map<std::string, TnCache::ptr> CacheMap;
    typedef std::pair<std::string, TnCache::ptr> CacheMapEntry;
    CacheMap m_cacheMap;
};

#endif

