# Source code of the Ubuntu-it website
# Copyright (C) 2015  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 json

import flask
import pkg_resources

from uitwww import cache


def get_pages_list(app, base=None, level=0):
    """Get the list of the pages, froma a directory"""
    root = os.path.join(app.root_path, app.template_folder)
    if base is None:
        base = os.path.join(root, "pages")

    pages = {}

    # Iterate over all templates
    for file in os.listdir(base):
        tmplpath = os.path.join(base, file)

        # Recursively scan sub-directories
        if os.path.isdir(tmplpath):
            pages.update(get_pages_list(app, tmplpath))
            continue

        url = tmplpath

        # Remove templates folder from the tmplpath
        if tmplpath.startswith(root):
            tmplpath = tmplpath[len(root)+1:]

        # Remove templates folder + pages folder from the url
        pagesdir = os.path.join(root, "pages")
        if url.startswith(pagesdir):
            url = url[len(pagesdir):]

        # Don't index hidden files
        if any(one.startswith(".") for one in url.split("/")):
            continue

        # Remove any index.html
        if url.endswith("index.html"):
            url = url[:-len("index.html")]

        # Remove any .html suffix
        if url.endswith(".html"):
            url = url[:-len(".html")]

        # Remove trailing slashes
        if len(url) > 1 and url.endswith("/"):
            url = url[:-1]

        pages[url] = tmplpath

    return pages


def prepare_blueprint(app):
    """Prepare a blueprint with all the pages"""
    bp = flask.Blueprint("pages", __name__)

    # Dynamically generate all the pages
    for url, tmpl in get_pages_list(app).items():

        endpoint = tmpl[len("pages_"):-len(".html")].replace("/", "_")

        @bp.route(url, endpoint=endpoint)
        @cache.enable
        def _(_tmpl=tmpl):
            return flask.render_template(_tmpl)

    return bp
