<%
/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you 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.
 */

var user = session.get('user');
var streamName;
var streamVersion;
var JaggeryWebSocketHelper = Packages.org.wso2.carbon.event.output.adapter.ui.JaggeryWebSocketHelper;

webSocket.onopen = function () {
    if (user == null) {
        this.close();
    }
};

webSocket.ontext = function (data) {
    streamName = data.split(':')[0];
    streamVersion = data.split(':')[1];
    JaggeryWebSocketHelper.subscribeWebSocket(streamName, streamVersion, "null",
                user.username, session.getId(), user.tenantId, this);
};

webSocket.onclose = function () {
    if (user != null && streamName != null && streamVersion != null) {     //onclose may get invoked when an invalid user (user==null case) closes the connection. Hence this check is required.
        JaggeryWebSocketHelper.unsubscribeWebsocket(streamName, streamVersion, session.getId(), user.tenantId);
    }
};

webSocket.onerror = function () {
    if (user != null) {
        JaggeryWebSocketHelper.unsubscribeWebsocket(streamId.split(":")[0], streamId.split(":")[1], session.getId(), user.tenantId);
    }
};

%>

