#/bin/bash
IGNORED_CAL="Birthdays, Family, Contacts, School, Home, Canadian Holidays, Canadiens, Jours fériés au Canada"
ALERT_IF_IN_NEXT_MINUTES=30
ALERT_POPUP_BEFORE_SECONDS=15
THEME_BG="#2c323c"
THEME_RED="#f92572"
NERD_FONT_FREE=""
NERD_FONT_MEETING="󰤙"
MEETING_DELIMITER=""
NERD_FONT_SEPARATOR=""

ICAL_BUDDY="/usr/local/bin/icalBuddy"

check_ical_buddy() {
    if [[ ! -f "$ICAL_BUDDY" ]]; then
        echo "Error: iCalBuddy is not installed" >&2
        return 1
    fi
}

get_next_meeting() {
    next_meeting=$("$ICAL_BUDDY" \
        --includeEventProps "title,datetime,attendees" \
        --propertyOrder "title,datetime" \
        --noCalendarNames \
        --dateFormat "%A" \
        --includeOnlyEventsFromNowOn \
        --limitItems 1 \
        --excludeAllDayEvents \
        --separateByDate \
        --excludeCals "$IGNORED_CAL" \
        eventsToday
    )

    if [[ -z "$next_meeting" ]]; then
        return 1
    fi

    echo "$next_meeting"
}

get_next_next_meeting() {
    end_timestamp=$(date +"%Y-%m-%d ${end_time}:01 %z")
    tonight=$(date +"%Y-%m-%d 23:59:00 %z")
    next_next_meeting=$("$ICAL_BUDDY" \
        --includeEventProps "title,datetime" \
        --propertyOrder "title,datetime" \
        --noCalendarNames \
        --dateFormat "%A" \
        --limitItems 1 \
        --excludeAllDayEvents \
        --separateByDate \
        --excludeCals "$IGNORED_CAL" \
        eventsFrom:"${end_timestamp}" to:"${tonight}"
    )

    if [[ -z "$next_meeting" ]]; then
        return 1
    fi
}

parse_result() {
    local ical_output="$1"

    start_time=""
    end_time=""
    attendees=""
    title=$(echo "$ical_output" | awk 'NR==3')
    lines=()

    # Use process substitution to emulate a file for the while loop
    while read -r line; do
        lines+=("$line")  # Store each line in the array for potential future use
        
        if [[ $line =~ [0-9]{2}:[0-9]{2}\ -\ [0-9]{2}:[0-9]{2} ]]; then
            start_time=$(echo "$line" | awk '{print $1}')
            end_time=$(echo "$line" | awk '{print $3}')
        fi

        if [[ $line == *attendees:* ]]; then
            attendees_line=${line#*attendees:}
            attendees=$(echo "$attendees_line" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//g')
            # Count the number of attendees
            num_attendees=$(echo "$attendees" | awk -F, '{print NF}')
        fi
    done < <(echo "$ical_output")
}

calculate_times() {
    if [[ -z "$start_time" ]]; then
        return 1
    fi

    epoc_meeting=$(date -jf "%T" "$start_time:00" +%s)
    if [[ $? -ne 0 ]]; then
        echo "Error: Failed to convert '$start_time' to epoch time" >&2
        return 2
    fi

    epoc_now=$(date +%s)

    epoc_diff=$((epoc_meeting - epoc_now))

    minutes_till_meeting=$((epoc_diff / 60))
}


get_upcoming_meetings() {
    upcoming_meetings=$("$ICAL_BUDDY" \
        --noCalendarNames \
        --formatOutput \
        --includeEventProps "title,datetime,attendees,notes,url" \
        --propertyOrder "title,datetime" \
        --includeOnlyEventsFromNowOn \
        --sortTagsByDate "Descending" \
        --excludeAllDayEvents \
        --bullet "$MEETING_DELIMITER" \
        --excludeCals "$IGNORED_CAL" \
        eventsToday)
    
    if [[ -z "$upcoming_meetings" ]]; then
        return 1
    fi
}

# get_last_meeting() {
#     get_upcoming_meetings
#
#     if [[ -z "$upcoming_meetings" ]]; then
#         return 1
#     fi
#
#     meetings=("${(s/$MEETING_DELIMITER/)upcoming_meetings}")
#
#     echo "meetings: ${meetings[@]}"
#
#     if [[ ${#meetings[@]} -eq 0 ]]; then
#         return 2
#     fi
#
#     last_meeting="${meetings[-1]}"
#     echo "$last_meeting"
# }

# Split the string into an array using the delimiter, in ZSH script
get_last_meeting() {
    get_upcoming_meetings

    if [[ -z "$upcoming_meetings" ]]; then
        return 1
    fi

    echo "upcoming_meetings: $upcoming_meetings"

    # Split the input by newline and remove leading/trailing whitespace
    IFS=$'\n' lines=($(echo "$input" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'))

    # Find the last line that contains "attendees:"
    last_attendees_line=""
    for line in ${(O)lines}; do
        if [[ $line == *attendees:* ]]; then
            last_attendees_line=$line
        fi
    done

    echo "last_attendees_line: $last_attendees_line"

    # Extract meeting information from the last attendees line
    if [[ -n "$last_attendees_line" ]]; then
        title=$lines[1]
        start_time=$(echo "$lines[2]" | awk '{print $1}')
        end_time=$(echo "$lines[2]" | awk '{print $3}')
        attendees=$(echo "$last_attendees_line" | sed 's/^[^:]*: //')

        # Store the meeting information in last_meeting
        last_meeting="Title: $title
        Start Time: $start_time
        End Time: $end_time
        Attendees: $attendees"

        # Print or use the extracted information as needed
        echo "$last_meeting"
    else
        echo "No meeting information found."
        return 1
    fi
    
    echo "last_meeting: $last_meeting"
    return "$last_meeting"
}


display_popup() {
    get_last_meeting

    if [[ -z "$last_meeting" ]]; then
        return 1
    fi

    tmux display-popup \
        -S "fg=$THEME_BG" \
        -w 50% \
        -h 50% \
        -T 'Meeting Reminder' \
        -d '#{pane_current_path}' \
        echo "$last_meeting"
}

print_tmux_status() {
    local tmux_refresh_interval=$(tmux show-option -g status-interval)
    local tmux_refresh_interval=$(echo "$tmux_refresh_interval" | awk '{print $NF}' | tr -d '[:space:]')
    local tmux_refresh_interval=$((tmux_refresh_interval))

    local print_alert="#[fg=$THEME_RED,bold,bg=$THEME_BG] \
$NERD_FONT_SEPARATOR \
$NERD_FONT_MEETING \
$start_time $title ($minutes_till_meeting minutes) "

    if ((ALERT_POPUP_BEFORE_SECONDS <= tmux_refresh_interval)); then
        echo "Error: ALERT_POPUP_BEFORE_SECONDS must be greater than tmux_refresh_interval" >&2
        return
    fi

    if ((minutes_till_meeting < ALERT_IF_IN_NEXT_MINUTES)) && ((epoc_diff > ALERT_POPUP_BEFORE_SECONDS)); then
        echo "$print_alert"
    elif ((epoc_diff <= ALERT_POPUP_BEFORE_SECONDS)) && ((epoc_diff > (ALERT_POPUP_BEFORE_SECONDS - tmux_refresh_interval))); then
        echo "$print_alert"
        display_popup
    else
        echo "#[bold,bg=$THEME_BG] $NERD_FONT_SEPARATOR $NERD_FONT_FREE "
    fi
}

main() {
    check_ical_buddy

    get_next_meeting

    parse_result "${next_meeting[@]}"

    calculate_times
    if [[ -n "${next_meeting[*]}" && $num_attendees -lt 2 ]]; then
        get_next_next_meeting

        parse_result "${next_next_meeting[@]}"

        calculate_times
    fi

    print_tmux_status
}

main

