#!/usr/bin/python3

import cgi
import cgitb
import json
import os
cgitb.enable()

tag = ""
try:
    form = cgi.FieldStorage(encoding='utf8')
    tag = form.getvalue('tag')
except:
    pass

# Zeug zeigen
print("Content-type: text/html\n")
print("<head><style>")
print("body {background-color: mintcream;}")
print("</style></head>")
print("""<h1 style="color:blue;">Tags</h1>""")
file_names= [f for f in os.listdir('posts') if os.path.isfile(os.path.join('posts', f))]
tag_set = []
if tag:
    for f in file_names:
        f = 'posts/' + f
        data = open(f, "r")
        data = json.load(data)
        if tag in data['tags']:
            print('<div style="background-color: mintcream; border: 5px solid seagreen; border-radius: 10px; padding: 10px;">')
            print(str(data['title']) + '<br>Datum: ' + str(data['published']))
            print('<hr>')
            print(str(data['content']) + '<br><hr>')
            for i in data['tags']:
                print('<a href="tags-show.py?tag=' + str(i) + '">#' + str(i) + '</a>')
            print('</div><br>')
else:
    print('<div style="background-color: mintcream; border: 5px solid seagreen; border-radius: 10px; padding: 10px;">')
    print("Tags<br>")
    for f in file_names:
        f = 'posts/' + f
        data = open(f, "r")
        tag_set += json.load(data)['tags']
    for i in sorted(set(tag_set)):
        print('<a href="tags-show.py?tag=' + str(i) + '">#' + str(i) + '</a><br>')
    print('</div><br>')

print()
print('<a href="posts-show.py">Alle Posts!</a><br>')
print('<a href="tags-show.py">Alle Tags anzeigen.</a><br>')
print('<a href="posts-create.py">Neuen Post verfassen!</a>')
