#! /usr/bin/env python3

# needs lowdown and feegden installed
# feedgen can be installed with pip
# also expects that *.md files are in blog/ directory

from feedgen.feed import FeedGenerator
import datetime
import subprocess
import os

blogs_dir = os.fsencode("blog")

#def blogposts_list_gen():
#    output_list = []
#    for file in os.listdir(blogs_dir):
#        filename = os.fsdecode(file)
#        if filename.endswith(".md"):
#            full_path = "blog/" + filename
#
#            author = subprocess.run("lowdown -X author " + full_path, capture_output=True, shell=True, text=True).stdout.strip()
#            title = subprocess.run("lowdown -X title " + full_path, capture_output=True, shell=True, text=True).stdout.strip()
#            time = subprocess.run("lowdown -X time " + full_path, capture_output=True, shell=True, text=True).stdout.strip()
#            content_html = subprocess.run("lowdown " + full_path, capture_output=True, shell=True, text=True).stdout.strip()
#
#            output_list.append([author, title, time, content_html, full_path])
#    return output_list

def events_list_gen():
    output_list = []
    events_file = open("dogadjaji.csv", "r")
    for line in events_file.readlines():
            date, time, location, title = line.split(", ")
            author = "Decentrala"
            content_html = f"Event is taking place at {location} on {date} at {time}. For more information see the forum at https://forum.dmz.rs"

            output_list.append([author, title, content_html])
    events_file.close()
    return output_list

def feedgen(blogs, events):
    fg_blog = FeedGenerator()
    fg_blog.id('http://dmz.rs/')
    fg_blog.title('Decentrala Blog')
    fg_blog.author( {'name':'Decentrala','email':'dmz@dmz.rs'} )
    fg_blog.link( href='https://dmz.rs/atom_blog.xml', rel='self' )

    fg_events = FeedGenerator()
    fg_events.id('http://dmz.rs/')
    fg_events.title('Decentrala Blog')
    fg_events.author( {'name':'Decentrala','email':'dmz@dmz.rs'} )
    fg_events.link( href='https://dmz.rs/atom_events.xml', rel='self' )

    for post in blogs:
        fe_blogs = fg_blog.add_entry()
        fe_blogs.id("https://dmz.rs/" + post[4][:-3] + ".html")
        fe_blogs.author({'name': post[0]})
        fe_blogs.title(post[1])
        fe_blogs.updated(post[2])
        fe_blogs.content(content=post[3], type='html')

    for event in events:
        fe_events = fg_events.add_entry()
        fe_events.id("https://dmz.rs/pages/events.html")
        fe_events.author({'name': event[0]})
        fe_events.title(event[1])
        fe_events.updated(datetime.datetime.now(datetime.timezone.utc))
        fe_events.content(content=event[2], type='html')

    fg_blog.atom_file('site/atom_blog.xml')
    fg_events.atom_file('site/atom_events.xml')