import logging
from djrandom.database import init_db
from djrandom.frontend import app, svcs
from djrandom.frontend.mailer import Mailer
from djrandom.frontend.search import Searcher
from djrandom.model.markov import MarkovModel
from djrandom.model.external import AlbumImageRetriever
from djrandom.frontend.latency import LatencyProfilerMiddleware
from werkzeug.contrib.cache import SimpleCache, MemcachedCache

log = logging.getLogger(__name__)


def create_app(opts, latency_profiler=False):
    init_db(opts.db_url, opts.solr_url)

    svcs['searcher'] = Searcher(opts.solr_url)
    svcs['album_images'] = AlbumImageRetriever(
        opts.lastfm_api_key, opts.album_art_dir)
    svcs['mailer'] = Mailer(opts.email_sender)
    if opts.memcached_url:
        svcs['cache'] = MemcachedCache([opts.memcached_url])
    else:
        svcs['cache'] = SimpleCache()
    svcs['markov'] = MarkovModel()
    try:
        svcs['markov'].load(opts.markov_data)
    except IOError, e:
        log.error('Could not read Markov data from %s: %s' % (
                opts.markov_data, str(e)))

    if latency_profiler:
        # Install our own latency profiler middleware.
        app.wsgi_app = LatencyProfilerMiddleware(
            app.wsgi_app,
            ['/json/album', '/json/song', '/album_image',
             '/json/playlist/get', '/json/playlist/by_title',
             '/json/playlist/list', '/user/activate', '/dl'])

    # Start the cProfile profiling middleware, if requested.
    if opts.profile:
        from repoze.profile.profiler import AccumulatingProfileMiddleware
        app.wsgi_app = AccumulatingProfileMiddleware(
            app.wsgi_app,
            log_filename='/var/tmp/djrandom-profile.log',
            cachegrind_filename='/var/tmp/djrandom-profile.cachegrind',
            discard_first_request=True,
            flush_at_shutdown=True,
            path='/__profile__'
            )

    # Set some configuration options in the Flask global config.
    app.config.from_pyfile(opts.app_config, silent=True)

    return app