import { MutableRefObject , useEffect } from 'react' ; import { useEventManager , useCalendarModelEventManager } from 'react-components' ; import { EVENT_ACTIONS } from 'proton-shared/lib/constants' ; import { CalendarEventManager , CalendarEventsEventManager } from 'proton-shared/lib/interfaces/calendar/EventManager' ; import { CalendarsEventsCache } from './interface' ; import removeCalendarEventStoreRecord from './cache/removeCalendarEventStoreRecord' ; import upsertCalendarApiEventWithoutBlob from './cache/upsertCalendarApiEventWithoutBlobs' ; export const useCalendarCacheEventListener = ( cacheRef , calendarIDs ) => { const { subscribe : standardSubscribe } = useEventManager ( ) ; const { subscribe : calendarSubscribe } = useCalendarModelEventManager ( ) ; useEffect ( ( ) => { return standardSubscribe ( ( { Calendars = [ ] } ) => { const cache = cacheRef . current ; if ( ! cache ) { return ; } const { calendars } = cache ; let actions = 0 ; Calendars . forEach ( ( { ID : CalendarID , Action } ) => { if ( Action === EVENT_ACTIONS . DELETE ) { delete calendars [ CalendarID ] ; actions ++ ; } } ) ; if ( actions ) { cacheRef . current . rerender ?. ( ) ; } } ) ; } , [ ] ) ; useEffect ( ( ) => { return calendarSubscribe ( calendarIDs , ( { CalendarEvents = [ ] } ) => { const cache = cacheRef . current ; if ( ! cache ) { return ; } const { calendars } = cache ; let actions = 0 ; CalendarEvents . forEach ( ( CalendarEventsChange ) => { if ( CalendarEventsChange . Action === EVENT_ACTIONS . DELETE ) { const calendarID = Object . keys ( calendars ) . find ( ( calendarID ) => { return calendars [ calendarID ] ?. events . has ( CalendarEventsChange . ID ) ; } ) ; const calendarsEventsCache = calendars [ calendarID || 'undefined' ] ; if ( ! calendarsEventsCache ) { return ; } removeCalendarEventStoreRecord ( CalendarEventsChange . ID , calendarsEventsCache ) ; actions ++ ; } if ( CalendarEventsChange . Action === EVENT_ACTIONS . UPDATE || CalendarEventsChange . Action === EVENT_ACTIONS . CREATE ) { const { CalendarID } = CalendarEventsChange . Event ; const calendarsEventsCache = calendars [ CalendarID ] ; if ( ! calendarsEventsCache ) { return ; } upsertCalendarApiEventWithoutBlob ( CalendarEventsChange . Event , calendarsEventsCache ) ; actions ++ ; } } ) ; if ( actions > 0 ) { cache . rerender ?. ( ) ; } } ) ; } , [ calendarIDs ] ) ; } ; export default useCalendarCacheEventListener ;