<%
/*
 * 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 log = new Log("/app/modules/enrollments/windows/agent-controller.jag");

var mdmProps = require("/app/modules/conf-reader/main.js")["conf"];
var UAParser = require("/app/modules/ua-parser.min.js")["UAParser"];
var tokenUtil = require("/app/modules/oauth/token-handlers.js")["handlers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var constants = require("/app/modules/constants.js");

var parser = new UAParser();
var userAgent = request.getHeader("User-Agent");
parser.setUA(userAgent);
parser.getResult();
var os = parser.getOS();
var platform = os.name;

if (platform != "Windows Phone" && platform != "Windows") {
    response.sendRedirect(mdmProps["appContext"] + "enrollments/error/unintentional-request");
} else if (session.get("lastAccessedPage") != "login-agent") {
    response.sendRedirect(mdmProps["appContext"] + "enrollments/error/unintentional-request");
} else {
    var username = request.getParameter("username");
    var email = session.get("email");
    var password = request.getParameter("password");
    var domain = request.getParameter("domain");
    if (!username || !email || !password) {
        response.sendRedirect(mdmProps["appContext"] + "enrollments/error/unintentional-request");
    } else {
        var authUrl = mdmProps["windowsConfigRoot"];
        var fullyQualifiedUsername = username;
        if(domain != null && domain != ''){
            fullyQualifiedUsername = username + "@" + domain;
        }
        tokenUtil.setupTokenPairByPasswordGrantType(fullyQualifiedUsername, password);
        var payload = {
            "credentials": {
                "username": username, "email": email,
                "password": password, "token": getAccessToken()
            }
        };
        serviceInvokers.XMLHttp.post(
                authUrl,
                stringify(payload),
                function (restAPIResponse) {
                    var status = restAPIResponse["status"];
                    if (status == 200) {
                        session.put("authenticatedUser", username);
                        session.put("windowsBinaryToken", parse(restAPIResponse["responseText"]).UserToken);
                        response.sendRedirect(mdmProps["appContext"] + "enrollments/windows/license-agent");
                    } else if (status == 403) {
                        response.sendRedirect(mdmProps["appContext"] + "enrollments/windows/login-agent?error=auth-failed");
                    } else if (status == 409) {
                        response.sendRedirect(mdmProps["appContext"] + "enrollments/windows/login-agent?" +
                        "error=auth-failed&message=Provided Workplace email does not match with username. Please check.");
                    } else {
                        // one visible possibility would be server sending 500
                        response.sendRedirect(mdmProps["appContext"] + "enrollments/windows/login-agent?error=unexpected");
                    }
                }
        );
    }
}


/**
 * This method reads the token pair from the session and return the access token.
 * If the token pair is not set in the session, this will return null.
 */
function getAccessToken() {
    var tokenPair = parse(session.get(constants["TOKEN_PAIR"]));
    if (tokenPair) {
        return tokenPair["accessToken"];
    } else {
        return null;
    }
};

%>