<%

/*
 * 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.
 */

include("util/constants.jag");
var log = new Log();
var multitenantUtils = Packages.org.wso2.carbon.utils.multitenancy.MultitenantUtils;

var cookie = request.getParameter("cookie");

var userStoreDomain = "PRIMARY";

var username = request.getParameter("user");
if(username != null) {
  session.put('user', username);
} else {
  username = session.get('user');
}

var tenantDomain = multitenantUtils.getTenantDomain(username);

// Remove tenant domain from the username.
username = multitenantUtils.getTenantAwareUsername(username);

// Extract the user store domain from the username, if there is one.
var usernameTokens = username.split('/');
if(usernameTokens.length > 1){
  userStoreDomain = usernameTokens[0];
  username = usernameTokens[1];
}

fetchData();
function fetchData(){

  if(cookie != null) {
    session.put('auth-cookie', cookie);
  }




  var Base64 = Packages.org.apache.commons.codec.binary.Base64;

  var str = new Packages.java.lang.String(USERNAME + ':' + PASSWORD);
  var base64 = Base64.encodeBase64(str.getBytes());

  var base64Str = new java.lang.String(base64);

  var headers = {"Authorization":"Basic " + base64Str, "Content-Type":"application/json"};

  data = {"tableName":"ORG_WSO2_IS_ANALYTICS_STREAM_ACTIVESESSIONS", "query":"tenantDomain:" + tenantDomain + " AND username:" + username + " AND userstoreDomain:" + userStoreDomain ,"start":0, "count":3};

  var jsonResult = post(DAS_SERVER_URL, stringify(data), headers,"json");
  var dataResult = jsonResult.data;

  var tableRows = new Array ();

   if(dataResult != null) {
      for (i = 0; i < dataResult.length; i++) {

        var obj = {};
        obj.IP = dataResult[i].values.remoteIp;
        obj.userAgent = dataResult[i].values.userAgent;
        obj.startTimestamp = new Date(dataResult[i].values.startTimestamp).toString("MMM dd");
        obj.sessionId = dataResult[i].values.sessionId;

        tableRows [i] = obj;
      }
   }
  print(tableRows);
}

%>
