# Copyright (c) 2024 Pedro Vílchez
# SPDX-License-Identifier: AGPL-3.0-or-later

# With the help of an (AI) LLM, hence, all humanity participated on this

from icalendar import Calendar, Event
import datetime

def ics_to_moinmoin_table(ics_file_paths):
    events = []
    # Define a color mapping for each calendar file
    color_map = {
        'wbmv15_main.ics':      '#D1D1FF',  # Light blue
        'wbmv15_talks.ics':     '#A2D5AB',  # Soft Green
        'wbmv15_workshops.ics': '#FFD580',  # Light Orange
    }

    # Process each calendar file
    for ics_file_path in ics_file_paths:
        with open(ics_file_path, 'rb') as file:
            cal = Calendar.from_ical(file.read())

        for component in cal.walk():
            if component.name == "VEVENT":
                summary = component.get('summary')
                start_dt = component.get('dtstart').dt
                end_dt = component.get('dtend').dt
                description = component.get('description', '-').replace('\n', ' <<BR>> ')

                event_details = {
                    'file': ics_file_path.split('/')[-1],  # Extract filename only
                    'start_dt': start_dt,
                    'end_dt': end_dt,
                    'summary': summary,
                    'description': description
                }
                events.append(event_details)

    # Sort events by start date and time
    events.sort(key=lambda x: x['start_dt'])

    # Building the MoinMoin table
    moinmoin_table = "||'''When'''||'''Title'''||'''Description'''||'''Attachments and links'''||\n"
    for event in events:
        date_time_str = event['start_dt'].strftime('%Y-%m-%d %H:%M')
        if event['start_dt'] != event['end_dt']:
            date_time_str += f"-{event['end_dt'].strftime('%H:%M')}"

        # Apply row style based on the event's source file using the color map
        row_color = color_map.get(event['file'], '#FFFFFF')  # Default to white if no match
        row_style = f"rowstyle=\"background-color: {row_color};\""

        moinmoin_table += f"||<style=\"white-space: nowrap;\" {row_style}>{date_time_str}||{event['summary']}||{event['description']} ||-||\n"

    return moinmoin_table

def main():
    # Example usage with multiple calendar files
    #   I used get-ics.sh script too
    ics_paths = ['wbmv15_main.ics', 'wbmv15_talks.ics', 'wbmv15_workshops.ics']
    wiki_content = ics_to_moinmoin_table(ics_paths)
    print(wiki_content)

if __name__ == "__main__":
    main()
