/*
    Copyright (c) 2018, WSO2 Inc. (http://wso2.com) All Rights Reserved.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

@App:name('APIM_ALERT_STAKEHOLDER')
@App:description('Store the alert subscribers information in the database')

@source(type = 'wso2event', wso2.stream.id = 'org.wso2.analytics.apim.alertStakeholderInfo:1.0.1', @map(type = 'wso2event'))
define stream AlertStakeholderInfoStream (
    userId string,
    alertTypes string,
    emails string,
    isSubscriber bool,
    isPublisher bool,
    isAdmin bool);

@PrimaryKey('userId','isSubscriber','isPublisher','isAdmin')
@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')
define table ApimAlertStakeholderInfo(userId string, alertTypes	string, emails	string, isSubscriber bool, isPublisher	bool, isAdmin	bool);

-- Data storing logic
from AlertStakeholderInfoStream 
select userId, alertTypes, emails, isSubscriber, isPublisher, isAdmin
update or insert into ApimAlertStakeholderInfo
set ApimAlertStakeholderInfo.alertTypes = alertTypes, ApimAlertStakeholderInfo.emails = emails
on ApimAlertStakeholderInfo.userId == userId and ApimAlertStakeholderInfo.isPublisher == isSubscriber and
    ApimAlertStakeholderInfo.isPublisher == isPublisher and ApimAlertStakeholderInfo.isAdmin == isAdmin;