/* Enter a unique ExecutionPlan */
@Plan:name('Android-Screen-ExecutionPlan')

@Plan:description('Identify screen on duration')


@Import('iot.per.device.stream.android.screen:1.0.0')
define stream ScreenStream (meta_owner string, meta_deviceId string, meta_timestamp long, state string);

@Export('iot.per.device.stream.android.screen.stats:1.0.0')
define stream ScreenStatsStream (meta_owner string, meta_deviceId string, meta_timestamp long, duration long, year int, month int, day int, hour int, minute int);

partition with (meta_deviceId of ScreenStream)
begin
    from every preState = ScreenStream[state == 'on'], postState = ScreenStream[state == 'off' AND preState.meta_timestamp <= meta_timestamp]
    select preState.meta_owner as meta_owner, preState.meta_deviceId as meta_deviceId, preState.meta_timestamp as meta_timestamp, (postState.meta_timestamp - preState.meta_timestamp) as duration,
	time:extract(preState.meta_timestamp, 'year') as year, time:extract(preState.meta_timestamp, 'month') as month, time:extract(preState.meta_timestamp, 'day') as day, time:extract(preState.meta_timestamp, 'hour') as hour, time:extract(preState.meta_timestamp, 'minute') as minute
    insert into ScreenStatsStream;
end;