# Source code of the Ubuntu-it website
# Copyright (C) 2023 shadMod
#
# 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
import locale
import markdown

from datetime import datetime

from ... import cache

CACHE_FILE = "news-cache.json"


class News:
    """
    :base_path: path

    :return:    [
                    {
                        "title": "Lorem Ipsum",
                        "author": "shadmod",
                        "mail": "m.allegro@shadmod.com",
                        "html": "html"
                    }
                ]
    :rtype:     list


    Sample file 000.md
    # Lorem Ipsum                       => title of newsletter, if not present takes
                                            the file progressive and year

    shadmod - m.allegro@shadmod.com     => author and mail of the same

    - Lorem ipsum dolor sit amet.       => body of newsletter
    - Aliquam tincidunt mauris.
    """

    def __init__(self):
        self.base_path = None

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

        # populate base_path
        self.base_path = os.path.join(app.instance_path, "news")

        @bp.route("/")
        @bp.route("/<year>")
        @cache.enable
        def index(year: int = None):
            news = []
            if year is None:
                data = {}
                for subdir in sorted(os.listdir(self.base_path), reverse=True):
                    data[subdir] = os.listdir(os.path.join(self.base_path, subdir))
                for year, file_list in data.items():
                    for file in file_list:
                        news.append(self.get_data(file, int(year)))
            else:
                dir_path = os.path.join(self.base_path, str(year))
                if os.path.exists(dir_path):
                    file_list = os.listdir(dir_path)
                    for file in file_list:
                        news.append(self.get_data(file, year))

            return flask.render_template(
                "news/index.html",
                news=news,
            )

        @bp.route("/<year>/<filename>")
        def detail(year: int, filename: str):
            return flask.render_template(
                "news/detail.html",
                news=self.get_data(f"{filename}.md", year)
            )

        return bp

    def get_data(self, filename: str, year: int = None):
        """
        :return:    {
                        "title": "Lorem Ipsum",
                        "author": "shadmod",
                        "mail": "m.allegro@shadmod.com",
                        "html": "html"
                    }
        :rtype:     dict
        """
        # init empty data
        data = {}
        # get complete path
        path = os.path.join(self.base_path, str(year), filename)
        # clean filename and set with 3 digits
        nr_file = str(filename.replace(".md", "")).zfill(3)
        # get last edit of file
        last_edit = os.stat(path).st_mtime

        try:
            # check and set with it_IT language
            if 'it_it' in locale.locale_alias:
                locale.setlocale(locale.LC_TIME, "it_IT.ISO8859-1")
        except:
            pass

        # format datetime: 01 Novembre 2023 - 00:00
        date_edit = datetime.fromtimestamp(last_edit)
        data["last_edit"] = date_edit.strftime("%d %B %Y - %H:%M")
        # set nr_news with nr file and relative year folder
        data["nr_news"] = f"{nr_file}/{year}"

        # 'compile' markdown in html
        with open(path, 'r') as f:
            tempHtml = markdown.markdown(f.read())
        # 'get' header and put in 'title' key
        html_tmp = tempHtml.split("\n")
        if "<h1>" in html_tmp[0]:
            data["title"] = html_tmp.pop(0).replace("<h1>", "").replace("</h1>", "")
        else:
            data["title"] = f"{year}.{nr_file}"
        # 'get' signature with author and mail and put in relative key
        if "<p>" in html_tmp[0]:
            data["author"], data["mail"] = html_tmp.pop(0).replace("<p>", "").replace("</p>", "").split(" - ")
        # what's left I put in html
        data["html"] = "".join(html_tmp)
        return data
