from bs4 import BeautifulSoup
import sys
import requests
from ics import Calendar
import arrow
import locale


# TODO: Handling missing arguments is way more complex in Python :(
if len(sys.argv) != 2:
    print("Usage: python3 {} <ICS_URL>".format(sys.argv[0]))

# TODO Reading from the same file as the output of this script is piped into leads to synchronization/buffering issues, we therefore have to do some quirks in entrypoint.sh
sourcefile = "/opt/lektor/project/content/contents.lr"

with open(sourcefile) as fp:
    soup = BeautifulSoup(fp, 'html.parser')

cols = soup.find_all('div', {'class' : 'nextevent'})

sourcestr = ""

if len(cols) != 1 :
    sourcestr = ""
else:
    sourcestr = str(cols[0])

with open(sourcefile, 'r') as file:
  file_contents = file.read()


url = sys.argv[1]

#TODO: Handling HTTP request or pasring errors is currently completely missing (although I implemented such a nice handling if the script would just gracefully continue on exceptions)
c = Calendar(requests.get(url).text)

locale.setlocale(locale.LC_TIME, locale.normalize("de_DE.UTF-8"))

colevents = list(c.timeline.start_after(arrow.now()))

if len(colevents) > 0 :
    weekday = colevents[0].begin.strftime("%A")
    date = colevents[0].begin.strftime("%-d. %B")
    time = colevents[0].begin.strftime(" %-H:%M") if not colevents[0].all_day else ""
    name = colevents[0].name
    location = " in " + colevents[0].location if colevents[0].location != None else "&nbsp;"
    replacestr = "<div class=\"nextevent\">{} <strong> {}{}, {}</strong>{}</div>".format(weekday, date, time, name, location)
else:
    replacestr = "<div class=\"nextevent\">Leider unbekannt, aber <strong>frag mal den Vorstand</strong> der müsste es wissen</div>"

if len(sourcestr) > 0 and sourcestr in file_contents:
    
    updated_contents = file_contents.replace(sourcestr, replacestr)
    print(updated_contents)
else:

    print("_model: htmlpage")
    print("---")
    print("title: Willkommen beim PC Stammertal")
    print("---")
    print("html:")
    print("")
    print("<h3>Unser nächster Anlass: </h3><br/>")
    print("<div class=\"nextevent\">Leider unbekannt, aber <strong>frag mal den Vorstand</strong> der müsste es wissen</div>")
    print("<div class=\"threecolumn\">")
    print("  <div>")
    print("    <a href=\"termine/\"><img src=\" /images/termine_square.jpg\" alt=\"Terminkalender\"> All unsere Termine</a>")
    print("  </div>")
    print("  <div>")
    print("    <a href=\"about/\"><img src=\"/images/about_square.jpg\" alt=\"Buch\"> Alle Infos über uns</a>")
    print("  </div>")
    print("  <div>")
    print("    <a href=\"kontakt/\"><img src=\"/images/kontakt_square.jpg\" alt=\"Briefe\"> Kontaktiere uns</a>")
    print("  </div>")
    print("</div>")
    print("---")
    print("_template:")
    print("")
    print("page.html")
    print("")
    print("")
