# Source code of the Ubuntu-it website
# 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 flask

from flask import request

from ... import cache
from .utils import GetNews

CACHE_FILE = "news-cache.json"


class News:

    def __init__(self, debug: bool = False):
        self.navs = []

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

        nw_cl = GetNews(os.path.join(app.instance_path, "news"))
        self.navs = nw_cl.category

        @bp.route("/")
        @cache.enable
        def list():
            req = request.args
            month = req.get("month")
            year = req.get("year")
            category = req.get("category")
            return flask.render_template(
                "news/list.html",
                news=nw_cl.list_news(year=year, category=category, month=month),
                list_years=nw_cl.list_year_month
            )

        @bp.route("/<year>/<category>/<filename>")
        @cache.enable
        def detail(year: str, category: str, filename: str):
            return flask.render_template(
                "news/detail.html",
                news=nw_cl.get_news(nr_file=filename, year=year, category=category)
            )

        return bp

    def generate_navbar(self):
        """Generate the sub-navbar for /news"""
        result = []
        for name in self.navs:
            result.append(
                {
                    "name": name.capitalize(),
                    "endpoint": "news.list",
                    "endpoint-args": {"category": name},
                }
            )
        return result
