# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

import logging
import os

from flask import Flask
from flask import request
from flask import send_from_directory
from flask_babel import Babel
from flask_menu import Menu

from xivo import http_helpers
from xivo_webi.auth import get_user
from xivo_webi.errors import configure_error_handlers


logger = logging.getLogger(__name__)


class FlaskController(object):

    def __init__(self, config):
        self._config = config
        self.app = Flask('xivo-webi')
        self.app.root_path = os.path.dirname(__file__)
        self.app.secret_key = config['secret_key']
        self.app.config.update(config)

        self.app.after_request(http_helpers.log_request)

        configure_error_handlers(self.app)
        http_helpers.add_logger(self.app, logger)

        self._configure_theme()
        self._configure_babel()
        self._configure_menu()
        self.app.context_processor(self._current_user_context_processor)

    def get_app(self):
        return self.app

    def _configure_theme(self):
        @self.app.context_processor
        def inject_theme():
            return dict(
                theme=self._config['theme']
            )

        theme_path = '{}/theme/{}'.format(self.app.static_url_path,
                                          self._config['theme'])

        @self.app.route(theme_path + '/<path:filename>')
        def static_theme(filename):
            return send_from_directory(self.app.root_path + theme_path, filename)

    def _configure_menu(self):
        menu = Menu()
        menu.init_app(self.app)

    def _configure_babel(self):
        babel = Babel()
        babel.init_app(self.app)
        self.app.config['BABEL_DEFAULT_LOCALE'] = 'en'

        @babel.localeselector
        def get_locale():
            translations = [str(translation) for translation in babel.list_translations()]
            return request.accept_languages.best_match(translations)

    def _current_user_context_processor(self):
        return dict(current_user=get_user())
