# 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 locale
import markdown

from datetime import datetime


class GetNews:
    """
    :param 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, base_path):
        self.base_path = base_path

    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.UTF-8")
        except Exception as ex:
            # TODO: add logger.warning(ex)
            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

    @property
    def list_files(self) -> list:
        data = []
        for list_files in self.get_all_files.values():
            data.extend(list_files)
        return data

    @property
    def get_all_files(self) -> dict:
        data = {}
        for subdir in sorted(os.listdir(self.base_path), reverse=True):
            data[subdir] = os.listdir(os.path.join(self.base_path, subdir))
        return data

    def get_all_files_counter(self, counter: int) -> dict:
        i = 0
        data = {}
        for year, list_news in self.get_all_files.items():
            if year not in data:
                data[year] = []
            for filename in list_news:
                data[year].append(filename)
                i += 1
                if i == counter:
                    break
            if i == counter:
                break
        return data

    def list_news(self, year=None):
        news = []
        if year is None:
            for year, file_list in self.get_all_files.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 news
