# -*- coding: utf-8 -*-
import os
from flask import Flask
from flask_api_auth import Authentication

# Have early access to the app object
app = Flask(__name__)

new_relic_config_file = '/home/webapp/code/project-distribution/distribution/newrelic.ini'

if os.path.exists(new_relic_config_file):
    import newrelic.agent
    newrelic.agent.initialize(new_relic_config_file)

import filters  # NOQA - Load custom filters
import logging.config  # NOQA
from flask_restful import Api  # NOQA
from distribution.logger.settings import LOGGING_CONFIG  # NOQA

app.config.from_object('distribution.settings')
app.url_map.strict_slashes = False

# load flask logger and set logging configuration
app.logger
logging.config.dictConfig(LOGGING_CONFIG)

from distribution.controllers import feed, health, sitemap  # NOQA

sentry_dsn = app.config.get('SENTRY_DSN')
if sentry_dsn:
    from raven.contrib.flask import Sentry
    sentry = Sentry(app, dsn=sentry_dsn)
    sentry_logger = logging.getLogger('distribution')
    handler = next(sentry_handler for sentry_handler in sentry_logger.handlers
                   if sentry_handler.__class__.__name__ == 'SentryHandler')
    handler.client = sentry.client

Authentication(app, '/api/v1')

api = Api(app)
api.add_resource(feed.Feed, '/feed/v1/', '/feed/v1/<adapter>/')
api.add_resource(feed.ValidateFeed, '/feed/v1/validate/')
api.add_resource(feed.DeletedFeed, '/feed/v1/deleted/')

api.add_resource(feed.FeedDetail, '/api/v1/item/<path:pk>/')
api.add_resource(feed.FeedDetailPost, '/api/v1/item/')

api.add_resource(feed.TaxonomyTopicDetail, '/api/v1/taxonomy_topics/<path:pk>/')
api.add_resource(feed.TaxonomyTopicList, '/api/v1/taxonomy_topics/')

api.add_resource(feed.SitemapURLDetail, '/api/v1/sitemap_url/<path:pk>/')
api.add_resource(feed.SitemapURLList, '/api/v1/sitemap_url/')

api.add_resource(feed.PublicAdapterDetail, '/public/<adapter>/<path:slug>/')
api.add_resource(sitemap.SitemapIndex, '/public/sitemap/<domain>/index.xml')
api.add_resource(sitemap.SitemapPage, '/public/sitemap/<domain>/items.<page>.xml')
api.add_resource(sitemap.SitemapNews, '/public/sitemap/<domain>/news.xml')

api.add_resource(health.Health, '/health/')
