<%
/*
 * Copyright (c) 2020, 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("../wsUtil.jag");
var util = require("../../util/utility.jag");
var multitenantUtils = Packages.org.wso2.carbon.utils.multitenancy.MultitenantUtils;

var log = new Log();
var serverUrl = util.getServerUrl();
serverUrl = serverUrl + "/RemoteUserStoreManagerService";
var cookie = session.get('auth-cookie');

function getUserClaim(userName, claim, profileName) {
    try {
        var ws = require("ws");
        var webService = new ws.WSRequest();
        var options = [];
        options.useSOAP = 1.2;
        options.action = "urn:getUserClaimValuesForClaims";
        options["HTTPHeaders"] = [
            {name: "cookie", value: cookie}
        ];
        var tenantAwareUserName = multitenantUtils.getTenantAwareUsername(userName);
        var payload = '<ser:getUserClaimValuesForClaims xmlns:ser="http://service.ws.um.carbon.wso2.org"><ser:userName>' + tenantAwareUserName + '</ser:userName><ser:claims>' + claim + '</ser:claims><ser:profileName>' + profileName + '</ser:profileName></ser:getUserClaimValuesForClaims>';

        webService.open(options, serverUrl, false);
        webService.send(payload);
        var resultJSON = E4XtoJSON(webService.responseE4X);
        return getClaimValue(resultJSON);
    } catch (e) {
        log.error(e);
    }
}

function getClaimValue(resultJSON) {

    var claimValue = "";
    if (resultJSON != "") {
        claimValue = resultJSON.return.value;
    }
    return claimValue;
}

%>
