<%

var log = new Log();

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

session.put('auth-cookie', cookie);

var userAccountAssociationClient = require('controllers/service-clients/userAccountAssociationClient.jag');
var identityProviderMgtClient = require('controllers/service-clients/identityProviderMgtClient.jag');
var userProfileMgtClient = require('controllers/service-clients/userProfileMgtClient.jag');
var identityProviderAdminClient = require('controllers/service-clients/identityProviderAdminClient.jag');
var userCoreUtils = Packages.org.wso2.carbon.user.core.util.UserCoreUtil;
var identityUtil = Packages.org.wso2.carbon.identity.core.util.IdentityUtil;


if (action != null) {
    if (action == 'list') {

        try {
            var fieldValues = userAccountAssociationClient.getAccountAssociationsOfUser();
            print('{"success":true, "data":' + getAssociatedAccounts(fieldValues) + '}');
        } catch (e) {
            print(getErrorMessage(e.message));
        }
    } else if (action == 'connect') {
        var userName = request.getParameter('userName');
        var password = request.getParameter('password');

        try {
            userAccountAssociationClient.createUserAccountAssociation(userName, password);
            print('{"success":true}');
        } catch (e) {
            print(getErrorMessage(e.message));
        }
    } else if (action == 'delete') {

        var userName = request.getParameter('userName');
        try {
            userAccountAssociationClient.deleteUserAccountAssociation(userName);
            print('{"success":true}');
        } catch (e) {
            print(getErrorMessage(e.message));
        }
    } else if (action == 'idPList') {

        try {
            var idPList = identityProviderMgtClient.getAllIdPs();
            print('{"success":true, "data":' + stringify(getIdPNameList(idPList)) + '}');
        } catch (e) {
            print(getErrorMessage(e.message));
        }
    } else if (action == 'fedConnect') {

        var isAllowed = identityUtil.isFederatedUserAssociationEnabled();

        if (isAllowed) {
            var idPId = request.getParameter('idPId');
            var username = request.getParameter('username');

            try {
                userProfileMgtClient.associateID(idPId, username);
                print('{"success":true}');
            } catch (e) {
                print(getErrorMessage(e.message));
            }
        } else {
            print(getErrorMessage('Error:Federated user association is not allowed in the server'));
        }
    } else if (action == 'associatedIdList') {

        var username = request.getParameter('username');
        try {
            var primaryOpenId = identityProviderAdminClient.getPrimaryOpenID(username);
            var fieldValues = userProfileMgtClient.getAssociatedIDs();
            print('{"success":true, "data":{ "primaryOpenID": "' + primaryOpenId.return + '", "list":' + getAssociatedFedAccounts(fieldValues) + '}}');
        } catch (e) {
            print(getErrorMessage(e.message));
        }
    } else if (action == 'fedDelete') {
        var idPId = request.getParameter('idPId');
        var username = request.getParameter('username');

        try {
            userProfileMgtClient.removeAssociateID(idPId, username);
            print('{"success":true}');
        } catch (e) {
            print(getErrorMessage(e.message));
        }
    }
}

function getErrorMessage(message) {
    if (message != null && message.length > 0) {
        if (message.indexOf('401 Error: Unauthorized') > -1) {
            return '{"success":false, "reLogin":true}';
        } else {
            var msg = message.split(':');
            if (msg.length > 0) {
                return '{"success":false, "message":"' + msg[1] + '"}';
            }
        }
    }
    return '{"success":false, "message":null}';
}

function getIdPNameList(idPList) {
    if (idPList != null && idPList.length > 0) {
        var idPNames = [];
        for (var i in idPList) {
            idPNames[i] = idPList[i].identityProviderName;
        }
        return idPNames;
    }
    return null;
}

function getAssociatedFedAccounts(accounts) {
    if (accounts != null && accounts.length > 0) {
        var accountsStr = "["
        for (var i in accounts) {
            accountsStr += "{\"idPName\":\"" + accounts[i].identityProviderName + "\"," +
                           "\"username\":\"" + accounts[i].username + "\"}";
            if ((parseInt(i) + 1) < accounts.length) {
                accountsStr += ",";
            }
        }
        accountsStr += ']';
        return accountsStr;
    }
    return null;
}

function getAssociatedAccounts(accounts) {
    if (accounts != null && accounts.length > 0) {
        var accountsStr = "["
        for (var i in accounts) {
            var username = userCoreUtils.addDomainToName(accounts[i].username, accounts[i].domain);
            username = userCoreUtils.addTenantDomainToEntry(username,accounts[i].tenantDomain)
            accountsStr += "{\"username\":\"" + accounts[i].username + "\"," +
                           "\"domain\":\"" + accounts[i].domain + "\"," +
                            "\"fullUsername\":\"" + username + "\"," +
                           "\"tenantDomain\":\"" + accounts[i].tenantDomain + "\"}";
            if ((parseInt(i) + 1) < accounts.length) {
                accountsStr += ",";
            }
        }
        accountsStr += "]";
        return accountsStr;
    }
    return null;
}

%>
