#! /usr/bin/env python3

import csv
from datetime import datetime

DAYS_SR = ["PON", "UTO", "SRE", "ČET", "PET", "SUB", "NED"]
DAYS_EN = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]
TYPES_DICT = {
    "hack": ("hakaton", "hackathon"),
    "lecture": ("predavanje", "lecture"),
    "workshop": ("radionica", "workshop"),
    "discussion": ("diskusija", "discussion"),
    "lighting": ("kratka predavanja", "short talks"),
    "movie": ("film", "movie"),
    "meeting": ("sastanak", "meeting"),
    "conference": ("konferencija", "conference"),
    "music": ("svirka", "gig"),
    "party": ("zabava", "entertainment"),
}

def load_events(csv_path:str) -> list[dict]:
    events = []
    with open(csv_path) as csv_file:
        csv_reader = csv.reader(csv_file, skipinitialspace=True)
        next(csv_reader, None)
        for event in csv_reader:
            event_date = event[0]
            event_date_parsed = datetime.strptime(event_date, "%d-%m-%Y").date()
            event_time = event[1]
            event_location = event[2]
            event_title = event[3]
            types =  event[4].split()
            try:
                link = event[5]
            except IndexError:
                link = ""
            current_event = {"date":event_date_parsed,
                             "time":event_time,
                             "location": event_location,
                             "title":event_title.strip(),
                             "types": types,
                             "link": link}
            events.append(current_event)
        return events

def build_html(events: list[dict], dayNames: list[str], typesNames: dict) -> str:
    events_html = []
    for event in events:
        title = event["title"]
        location = event["location"]
        date = event["date"]
        date = dayNames[date.weekday()]+", "+str(date.day)+". "+str(date.month)+". "+str(date.year)+", "
        time = event["time"]+"h"
        event_html = []
        event_html.append(f"<div class='date'>{date} {time}</div>")
        if event["link"] != "":
            event_html.append(f"<div class='title'><a href=\"{event['link']}\">{title}</a></div>")
        else:
            event_html.append(f"<div class='title'>{title}</div>")
        if "https://" in location:
            place,link = location.split("https://")
            event_html.append(f"<div class='place'><a href=\"https://{link}\">@{place.strip()}</a></div>")
        else:
            event_html.append(f"<div class='place'>@{location.strip()}</div>")

        if len(event["types"]) != 0:
            types_list = "<div class='types'>"
            last_item = event["types"][-1]
            for t in event["types"]:
                if typesNames.get(t) is not None:
                    types_list += typesNames.get(t)
                    if t != last_item:
                        types_list += ', '
                else:
                    print(f"Unknown type {t}!")
            types_list += "</div>"
            event_html.append(types_list)

        event_html = "".join(event_html)
        events_html.append(f"\n<div class='event'>{event_html}</div>")
    return events_html

def build_ical(events: list[dict]) -> str:
    today = datetime.today().now()
    # Header
    events_ical = ""
    with open("template/head.ical", "r") as file:
        events_ical += file.read()
    # Events
    for event in events:
        title = event["title"]
        location = event["location"]
        date = event["date"]
        time = event["time"]
        url = event["link"]

        uid = str(date.month).zfill(2) + str(date.day).zfill(2) + time[:2]
        date = str(date.year) + str(date.month).zfill(2) + str(date.day).zfill(2) 
        created = str(today.year) + str(today.month).zfill(2) + str(today.day).zfill(2) + "T" + str(today.hour).zfill(2) + str(today.minute).zfill(2) + str(today.second).zfill(2) + "Z"
        date = date + "T" + time.replace(":", "") + "00"

        event_template = ""
        with open("template/event.ical", "r") as file:
            event_template += file.read()
        event_template = event_template.replace("<!--UID-->", uid)
        event_template = event_template.replace("<!--CREATED-->", created)
        event_template = event_template.replace("<!--DATE-->", date)
        event_template = event_template.replace("<!--TITLE-->", title)
        event_template = event_template.replace("<!--URL-->", url)

        events_ical += event_template
    # Footer
    with open("template/end.ical", "r") as file:
        events_ical += file.read()
    return events_ical

events = sorted(load_events("dogadjaji.csv"), key=lambda e: e["date"])

today = datetime.today().date()

past_events = list(filter(lambda e: e["date"] <= today, events))
past_events.reverse()
new_events  = list(filter(lambda e: e["date"] >= today, events))


page_template = ""

sr_types = {}
en_types = {}

for key, value_pair in TYPES_DICT.items():
    sr_types[key] = value_pair[0]
    en_types[key] = value_pair[1]

# Build Serbian Events page
new_events_html = build_html(new_events, DAYS_SR, sr_types)
with open("pages/sr/events.html", "r") as file:
    page_template = ([line for line in file])

with open("pages/sr/events.html", "w") as file:
    file.writelines(page_template + new_events_html)

# Build English Events page
new_events_html = build_html(new_events, DAYS_EN, en_types)
with open("pages/en/events.html", "r") as file:
    page_template = ([line for line in file])

with open("pages/en/events.html", "w") as file:
    file.writelines(page_template + new_events_html)

# Build Serbian Archive page
past_events_html = build_html(past_events, DAYS_SR, sr_types)
with open("pages/sr/events_archive.html", "r") as file:
    page_template = ([line for line in file])

with open("pages/sr/events_archive.html", "w") as file:
    file.writelines(page_template + past_events_html)

# Build English Archive page
past_events_html = build_html(past_events, DAYS_EN, en_types)
with open("pages/en/events_archive.html", "r") as file:
    page_template = ([line for line in file])

with open("pages/en/events_archive.html", "w") as file:
    file.writelines(page_template + past_events_html)

new_events_ical = build_ical(new_events)

# Build ical
with open("site/events.ical", "w") as file:
    file.write(build_ical(new_events))