#!/usr/bin/env bash

# Get call length in seconds
CALL_LENGTH="$TUPLE_TRIGGER_CALL_LENGTH"

# Get the current time and calculate the start time
CURRENT_TIME=$(date -u +"%Y%m%dT%H%M%SZ")
START_TIME=$(date -v-${CALL_LENGTH}S -u +"%Y%m%dT%H%M%SZ")

# AppleScript for input dialog to get the title of the event
EVENT_TITLE=$(osascript -e 'Tell application "System Events" to display dialog "Enter the title of the event for Google Calendar:" default answer ""' -e 'text returned of result' 2>/dev/null)

# Check if the user canceled or didn't enter a title
if [ -z "$EVENT_TITLE" ]; then
  echo "No title entered. Exiting script."
  exit 0
fi

# Remove newlines and carriage returns, then URL encode the title
ENCODED_TITLE=$(printf '%s' "$EVENT_TITLE" | tr -d '\n\r' | python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.stdin.read()))')

# Create the Google Calendar event URL with the user-entered title
CALENDAR_URL="https://calendar.google.com/calendar/render?action=TEMPLATE&text=$ENCODED_TITLE&details=Tuple%20Call&dates=$START_TIME/$CURRENT_TIME"

# Prompt the user to add the event to Google Calendar
RESPONSE=$(osascript -e 'Tell application "System Events" to display dialog "Add this event to Google Calendar?\n\n'"$EVENT_TITLE"'" buttons {"Cancel", "Add to Calendar"} default button "Add to Calendar"' -e 'button returned of result' 2>/dev/null)

# Check if user confirmed to add the event to Google Calendar
if [ "$RESPONSE" = "Add to Calendar" ]; then
  # Open the URL in the default web browser
  open "$CALENDAR_URL"
else
  echo "User canceled the action. Exiting script."
fi
