# Source code of the Ubuntu-it website
# Copyright (C) 2015 Pietro Albini <pietroalbini@ubuntu.com>
# Copyright (C) 2023 shadMod <m.allegro@shadmod.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; without 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 toml
import flask

from uitwww import cache
from .src.news.utils import GetNews


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__)
    data_path = os.path.expanduser(os.path.abspath("data"))

    def list_news():
        nw_cl = GetNews(os.path.join(app.instance_path, "news"))
        _list_news = nw_cl.get_all_files_counter(4)
        return _list_news

    def list_distro():
        path = os.path.join(data_path, "downloads.toml")
        distros = toml.load(path)['distros']
        distros.pop('desktop')
        distros.pop('live-server')
        return distros

    # 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,
                news=list_news(),
                distros=list_distro()
            )

    return bp
