create context PerDriver partition by driverKey from TachographVehicleUsageIntervalInputEvent;

create schema VuCardAbsentInterval(
    sessionId java.util.UUID,
    driverKey string,
    startedAtEpochSecond long,
    endedAtEpochSecond long,
    durationSeconds long,
    previousUsageIntervalId string,
    nextUsageIntervalId string,
    previousRegistrationKey string,
    nextRegistrationKey string,
    previousVehicleKey string,
    nextVehicleKey string
);

context PerDriver
create window PreviousVehicleUsageInterval#lastevent as TachographVehicleUsageIntervalInputEvent;

@Priority(30)
context PerDriver
on TachographVehicleUsageIntervalInputEvent as next
insert into VuCardAbsentInterval
select
    priorInterval.sessionId as sessionId,
    priorInterval.driverKey as driverKey,
    priorInterval.endedAtEpochSecond + 1L as startedAtEpochSecond,
    next.startedAtEpochSecond as endedAtEpochSecond,
    next.startedAtEpochSecond - (priorInterval.endedAtEpochSecond + 1L) as durationSeconds,
    priorInterval.lastSourceIntervalId as previousUsageIntervalId,
    next.firstSourceIntervalId as nextUsageIntervalId,
    priorInterval.registrationKey as previousRegistrationKey,
    next.registrationKey as nextRegistrationKey,
    priorInterval.vehicleKey as previousVehicleKey,
    next.vehicleKey as nextVehicleKey
from PreviousVehicleUsageInterval as priorInterval
where priorInterval.endedAt is not null
  and next.startedAt is not null
  and next.startedAtEpochSecond > priorInterval.endedAtEpochSecond + 1L;

@Priority(20)
context PerDriver
on TachographVehicleUsageIntervalInputEvent
delete from PreviousVehicleUsageInterval;

@Priority(10)
context PerDriver
on TachographVehicleUsageIntervalInputEvent as current
insert into PreviousVehicleUsageInterval
select *;

@name('vuCardAbsentIntervals')
select * from VuCardAbsentInterval;
