from bs4 import BeautifulSoup
import sys
from datetime import datetime, date
import recurring_ical_events
import requests
from icalendar import Calendar
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"

fallbackreplacestr = "<div class=\"nextevent\">Leider unbekannt, aber <strong>frag mal den Vorstand</strong> der müsste es wissen</div>"

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]

locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')

#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)
response = requests.get(url)
calendar = Calendar.from_ical(response.content)

# Get recurring and non-recurring events
events = recurring_ical_events.of(calendar).after(datetime.now())

try:
    event = next(events)


    start = event.get('dtstart').dt
    out_summary = event.get('summary')
    location = event.get('location', 'No location specified')
    
    out_weekday = start.strftime("%A")
    out_startdate = start.strftime("%-d. %B")

    # Format output based on whether it's an all-day event
    if isinstance(start, date) and not isinstance(start, datetime):
        out_starttime = ""
    else:
        out_starttime = start.strftime(" %-H:%M")
        
    if location != 'No location specified':
        out_location = f", {location}"
    else:
        out_location = ""

    replacestr = "<div class=\"nextevent\">{} <strong> {}{}, {}</strong>{}</div>".format(out_weekday, out_startdate, out_starttime, out_summary, out_location)

except StopIteration:

    replacestr = fallbackreplacestr

# Why should we check if sourcestring is in the file when it originates from there?!?
# Because theoretically it could be that BeautifulSoup extracts it slightly different (sepcial characters or such).
# And as here we do a simple replace it wouldn't catch anything if it isn't an exact match.
# Also an empty string is a perfect match and matches in the wrong place, therefore we check for a minimal length > 0
# TODO: Most probably replacement could be done by BeautifulSoup too.
# But as this is a collection of StackOverflow roadkill rather than fine crafted menu of purest python ingredients, that's just what I could catch most easily.

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(fallbackreplacestr)
    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("")
