use std::cmp::Ordering;
use std::ptr;
use serde::{Deserialize, Serialize};
use crate::alarm::EKAlarm;
use crate::calendar::EKCalendar;
use crate::error::EventKitError;
use crate::event_store::EKEventStore;
use crate::ffi;
use crate::object::EKObject;
use crate::participant::EKParticipant;
use crate::private::{json_cstring, parse_json_ptr, redacted, Redacted};
use crate::recurrence_rule::EKRecurrenceRule;
use crate::structured_location::EKStructuredLocation;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum EKEventAvailability {
NotSupported,
#[default]
Busy,
Free,
Tentative,
Unavailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum EKEventStatus {
#[default]
None,
Confirmed,
Tentative,
Canceled,
}
#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EKEvent {
pub identifier: Option<String>,
pub title: String,
pub start_date: String,
pub end_date: String,
pub calendar_identifier: Option<String>,
pub calendar: Option<EKCalendar>,
pub notes: Option<String>,
pub location: Option<String>,
#[serde(default)]
pub alarms: Vec<EKAlarm>,
#[serde(default)]
pub recurrence_rules: Vec<EKRecurrenceRule>,
pub calendar_item_identifier: Option<String>,
pub calendar_item_external_identifier: Option<String>,
pub url: Option<String>,
pub last_modified_date: Option<String>,
pub creation_date: Option<String>,
pub time_zone_identifier: Option<String>,
pub has_alarms: bool,
pub has_recurrence_rules: bool,
pub has_attendees: bool,
pub has_notes: bool,
#[serde(default)]
pub attendees: Vec<EKParticipant>,
pub all_day: bool,
pub structured_location: Option<EKStructuredLocation>,
pub organizer: Option<EKParticipant>,
pub availability: EKEventAvailability,
pub status: EKEventStatus,
pub is_detached: bool,
pub occurrence_date: Option<String>,
pub birthday_contact_identifier: Option<String>,
pub birthday_person_unique_id: Option<String>,
}
impl core::fmt::Debug for EKEvent {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("EKEvent")
.field("identifier", &self.identifier)
.field("title", &Redacted)
.field("start_date", &self.start_date)
.field("end_date", &self.end_date)
.field("calendar_identifier", &self.calendar_identifier)
.field("calendar", &self.calendar)
.field("notes", &redacted(self.notes.as_ref()))
.field("location", &redacted(self.location.as_ref()))
.field("alarms", &self.alarms)
.field("recurrence_rules", &self.recurrence_rules)
.field("calendar_item_identifier", &self.calendar_item_identifier)
.field(
"calendar_item_external_identifier",
&self.calendar_item_external_identifier,
)
.field("url", &redacted(self.url.as_ref()))
.field("last_modified_date", &self.last_modified_date)
.field("creation_date", &self.creation_date)
.field("time_zone_identifier", &self.time_zone_identifier)
.field("has_alarms", &self.has_alarms)
.field("has_recurrence_rules", &self.has_recurrence_rules)
.field("has_attendees", &self.has_attendees)
.field("has_notes", &self.has_notes)
.field("attendees", &self.attendees)
.field("all_day", &self.all_day)
.field("structured_location", &self.structured_location)
.field("organizer", &self.organizer)
.field("availability", &self.availability)
.field("status", &self.status)
.field("is_detached", &self.is_detached)
.field("occurrence_date", &self.occurrence_date)
.field(
"birthday_contact_identifier",
&redacted(self.birthday_contact_identifier.as_ref()),
)
.field(
"birthday_person_unique_id",
&redacted(self.birthday_person_unique_id.as_ref()),
)
.finish()
}
}
impl EKEvent {
pub fn new(
title: impl Into<String>,
start_date: impl Into<String>,
end_date: impl Into<String>,
) -> Self {
Self {
identifier: None,
title: title.into(),
start_date: start_date.into(),
end_date: end_date.into(),
calendar_identifier: None,
calendar: None,
notes: None,
location: None,
alarms: Vec::new(),
recurrence_rules: Vec::new(),
calendar_item_identifier: None,
calendar_item_external_identifier: None,
url: None,
last_modified_date: None,
creation_date: None,
time_zone_identifier: None,
has_alarms: false,
has_recurrence_rules: false,
has_attendees: false,
has_notes: false,
attendees: Vec::new(),
all_day: false,
structured_location: None,
organizer: None,
availability: EKEventAvailability::Busy,
status: EKEventStatus::None,
is_detached: false,
occurrence_date: None,
birthday_contact_identifier: None,
birthday_person_unique_id: None,
}
}
pub fn with_calendar_identifier(mut self, calendar_identifier: impl Into<String>) -> Self {
self.calendar_identifier = Some(calendar_identifier.into());
self
}
pub fn with_all_day(mut self, all_day: bool) -> Self {
self.all_day = all_day;
self
}
pub fn with_structured_location(mut self, structured_location: EKStructuredLocation) -> Self {
self.structured_location = Some(structured_location);
self
}
pub fn compare_start_date(&self, other: &Self) -> Result<Ordering, EventKitError> {
let lhs = json_cstring(self, "EKEvent")?;
let rhs = json_cstring(other, "EKEvent")?;
let mut error = ptr::null_mut();
let value = unsafe {
ffi::event::ek_event_compare_start_date_json(lhs.as_ptr(), rhs.as_ptr(), &raw mut error)
};
if error.is_null() {
Ok(match value {
x if x < 0 => Ordering::Less,
0 => Ordering::Equal,
_ => Ordering::Greater,
})
} else {
Err(unsafe { EventKitError::from_error_ptr(error, "compareStartDateWithEvent failed") })
}
}
pub fn roundtrip_in(&self, store: &EKEventStore) -> Result<Self, EventKitError> {
let payload = json_cstring(self, "EKEvent")?;
let mut error = ptr::null_mut();
let json = unsafe {
ffi::event::ek_event_roundtrip_json(
store.as_raw_ptr(),
payload.as_ptr(),
&raw mut error,
)
};
if json.is_null() {
Err(unsafe { EventKitError::from_error_ptr(error, "event roundtrip failed") })
} else {
unsafe { parse_json_ptr(json, "EKEvent") }
}
}
pub fn as_object_in(&self, store: &EKEventStore) -> Result<EKObject, EventKitError> {
EKObject::from_event(store, self)
}
pub fn refresh_in(&self, store: &EKEventStore) -> Result<Option<Self>, EventKitError> {
let Some(identifier) = &self.identifier else {
return Ok(None);
};
store.refresh_event_occurrence(identifier, self.occurrence_date.as_deref())
}
}
#[cfg(test)]
mod tests {
use std::cmp::Ordering;
use super::*;
#[test]
fn event_status_round_trips_through_json() {
let value = serde_json::to_string(&EKEventStatus::Tentative).unwrap();
let decoded: EKEventStatus = serde_json::from_str(&value).unwrap();
assert_eq!(decoded, EKEventStatus::Tentative);
}
#[test]
fn event_builder_sets_defaults() {
let event = EKEvent::new("Demo", "2026-01-01T10:00:00Z", "2026-01-01T11:00:00Z");
assert_eq!(event.title, "Demo");
assert_eq!(event.availability, EKEventAvailability::Busy);
assert_eq!(event.status, EKEventStatus::None);
assert!(!event.all_day);
assert!(!event.has_alarms);
}
#[test]
fn event_builder_helpers_set_optional_fields() {
let location = EKStructuredLocation::new("HQ");
let event = EKEvent::new("Demo", "2026-01-01T10:00:00Z", "2026-01-01T11:00:00Z")
.with_calendar_identifier("calendar-1")
.with_all_day(true)
.with_structured_location(location);
assert_eq!(event.calendar_identifier.as_deref(), Some("calendar-1"));
assert!(event.all_day);
assert_eq!(
event.structured_location.and_then(|value| value.title),
Some("HQ".to_owned())
);
}
#[test]
fn events_compare_by_start_date() {
let earlier = EKEvent::new("Earlier", "2026-01-01T09:00:00Z", "2026-01-01T10:00:00Z");
let later = EKEvent::new("Later", "2026-01-01T11:00:00Z", "2026-01-01T12:00:00Z");
assert_eq!(earlier.compare_start_date(&later).unwrap(), Ordering::Less);
}
}