# Source code of the Ubuntu-it website
# Copyright (C) 2015-2016  Pietro Albini <pietroalbini@ubuntu.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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; witout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os

import flask

from . import pages
from . import cache


def create_app(data_path):
    """Create a new instance of the application"""
    app = flask.Flask(__name__, static_url_path="/+assets")
    app.config["DATA_PATH"] = data_path

    app.config["CACHE_PATH"] = os.path.join(data_path, "cache")
    cache.install_cache(app)

    app.register_blueprint(pages.prepare_blueprint(app))
    pages.prepare_navbar(app)

    @app.errorhandler(404)
    def not_found(error):
        return flask.render_template("404.html"), 404

    return app


def init_data_directory(data_path):
    """Initialize the data directory"""
    src_directory = os.path.dirname(os.path.abspath(__file__))

    # Create all the directories
    dirs = ["", "cache"]
    for dir in dirs:
        os.makedirs(os.path.join(data_path, dir), exist_ok=True)

    # Initialize the cache
    static_dirs = {"static": "+assets"}
    for src, dest in static_dirs.items():
        dest = os.path.join(data_path, "cache", dest)

        # Create the correct symlink
        if os.path.exists(dest):
            os.remove(dest)
        os.symlink(os.path.join(src_directory, src), dest)
