import frmWrk.website as website
import feed_generator
import pathlib
from time import sleep

article_base_html = ""
with open("src/article.html") as article_html:
    article_base_html = article_html.read()

articles_base_html = ""
with open("src/articles.html") as articles_html:
    articles_base_html = articles_html.read()

def article_list():
    article_paths = (pathlib.Path.cwd() / "feed_articles").glob("[0-9]*")
    article_paths_sorted = sorted(article_paths, key=lambda x: x.name, reverse=True)
    
    metadatas = [(feed_generator.convert_markdown_to_html(path)[1], path.parts[-1]) for path in article_paths_sorted] 
    print(metadatas)

    elements = ['<li><a href="articles.html?{guid}">{title} ({guid})</a></li>'.format(title=metadata[0]["title"][0], guid=metadata[1]) for metadata in metadatas]

    return articles_base_html.format(elements="\n".join(elements))

def article(path):
    if not "?" in path:
        return article_list()
    
    article_name = path.split("?")[1]
    article_html = feed_generator.convert_markdown_to_html(pathlib.Path("feed_articles") / article_name)

    return article_base_html.format(body=article_html[0])

if __name__ == "__main__":
    webserver = website.WebServer("", 3000, "./src", overwrites={"/articles.html": article})

    webserver.start()

    while True:
        feed = feed_generator.make_rss_feed("feed_articles", "Vantens", "https://vanten-s.com/", "Vantens personal feed")
        with open("src/rss.xml", "w") as f:
            f.write(feed)

        try:
            sleep(15)

        except KeyboardInterrupt:
            break

    webserver.close()

