<%
/*
 * 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 uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));

var log = new Log("api/device-api.jag");
var constants = require("/app/modules/constants.js");
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];

var user = session.get(constants.USER_SESSION_KEY);
var result;

response.contentType = 'application/json';

if (!user) {
    response.sendRedirect("/devicemgt/login?#login-required");
    exit();
} else {
    if (uriMatcher.match("/{context}/api/devices/sketch/download")) {
        // works as a proxy to pass the relavant query string to back end api.
        var queryString = request.getQueryString();
        if (!queryString) {
            queryString = "";
        } else {
            queryString = "?" + queryString;
        }
        var deviceType = request.getParameter("deviceType"); // need a better solution here
        deviceTypeConfig = utility.getDeviceTypeConfig(deviceType);
        if (deviceTypeConfig && deviceTypeConfig.deviceType.downloadAgentUri) {
            hearders = [{"name": constants["ACCEPT_IDENTIFIER"], "value": constants["APPLICATION_ZIP"]}];
            sketchDownloadEndPoint = devicemgtProps["httpsURL"] + "/" + deviceTypeConfig.deviceType.downloadAgentUri;
            serviceInvokers.HttpClient.get(sketchDownloadEndPoint + queryString, function (responsePayload, responseHeaders) {
                                               if (responseHeaders) {
                                                   for (var i = 0; i < responseHeaders.length; i++) {
                                                       var header = responseHeaders[i];
                                                       var headerName = String(header.getName());
                                                       var headerValue = String(header.getValue());
                                                       response.addHeader(headerName, headerValue);
                                                   }
                                                   var streamObject = new Stream(responsePayload);
                                                   print(streamObject);
                                               } else {
                                                   return responsePayload;
                                               }
                                           }, function (responsePayload) {
                                               log.error(responsePayload);
                                               var response = {};
                                               response["status"] = "error";
                                               return response;
                                           }
                , hearders);
        } else {
            result = 400;
        }
    } else if (uriMatcher.match("/{context}/api/devices/all")) {
        result = deviceModule.getOwnDevices();

    } else if (uriMatcher.match("/{context}/api/devices/count")) {
        var count = deviceModule.getOwnDevicesCount().data;
        result = count.toString();

    } else if (uriMatcher.match("/{context}/api/devices/types")) {
        result = deviceModule.listDeviceTypes();

    } else if (uriMatcher.match("/{context}/api/devices/{deviceType}/{deviceId}/remove")) {
        var elements = uriMatcher.elements();
        var deviceId = elements.deviceId;
        var deviceType = elements.deviceType;
        result = deviceModule.removeDevice(deviceType, deviceId);

    } else if (uriMatcher.match("/{context}/api/devices/{deviceType}/{deviceId}/update")) {
        var elements = uriMatcher.elements();
        var deviceId = elements.deviceId;
        var deviceType = elements.deviceType;
        var deviceName = request.getParameter("name");
        result = deviceModule.updateDevice(deviceType, deviceId, deviceName);
    } else if (uriMatcher.match("/{context}/api/devices")) {
        var url = request.getParameter("url");
        var draw = request.getParameter("draw");
        var length = request.getParameter("length");
        var start = request.getParameter("start");
        var search = request.getParameter("search[value]");
        var deviceName = request.getParameter("columns[1][search][value]");
        var owner = request.getParameter("columns[2][search][value]");
        var status = request.getParameter("columns[3][search][value]");
        var platform = request.getParameter("columns[4][search][value]");
        var ownership = request.getParameter("columns[5][search][value]");
        var targetURL;

        function appendQueryParam (url, queryParam , value) {
            if (url.indexOf("?") > 0) {
                return url + "&" + queryParam + "=" + value;
            }
            return url + "?" + queryParam + "=" + value;
        }
        targetURL = devicemgtProps.httpsURL + request.getParameter("url");
        targetURL = appendQueryParam(targetURL, "draw", draw);
        targetURL = appendQueryParam(targetURL, "start", start);
        targetURL = appendQueryParam(targetURL, "length", length);

        if (search && search !== "") {
            targetURL = appendQueryParam(targetURL, "search", search);
        }

        if (deviceName && deviceName !== "") {
            targetURL = appendQueryParam(targetURL, "device-name", deviceName);
        }

        if (owner && owner !== "") {
            targetURL = appendQueryParam(targetURL, "user", owner);
        }

        if (status && status !== "") {
            targetURL = appendQueryParam(targetURL, "status", status);
        }

        if (platform && platform !== "") {
            targetURL = appendQueryParam(targetURL, "type", platform);
        }

        if (ownership && ownership !== "") {
            targetURL = appendQueryParam(targetURL, "ownership", ownership);
        }

        serviceInvokers.XMLHttp.get(
            targetURL, function (responsePayload) {
                response.status = 200;
                result =  responsePayload;
            },
            function (responsePayload) {
                response.status = responsePayload.status;
                result =  responsePayload.responseText;
            });
    } else if (uriMatcher.match("/{context}/api/devices/")) {
        if (userModule.isAuthorized("/permission/admin/device-mgt/devices/list")) {
            result = deviceModule.listDevices();
        } else {
            response.sendError(403);
        }
    } else if (uriMatcher.match("/{context}/api/devices/{type}/{deviceId}")) {
        elements = uriMatcher.elements();
        deviceId = elements.deviceId;
        type = elements.type;
        if (userModule.isAuthorized("/permission/admin/device-mgt/devices/list")) {
            result = deviceModule.viewDevice(type, deviceId);
        }else {
            response.sendError(403);
        }
    } else if (uriMatcher.match("/{context}/api/devices/agent/{type}/{deviceId}/config")) {
        elements = uriMatcher.elements();
        deviceId = elements.deviceId;
        type = elements.type;
        operation = elements.operation;
        if (userModule.isAuthorized("/permission/admin/device-mgt/devices/owning-device")) {
            result = deviceModule.getDeviceAgentConfig(type, deviceId);
            if (!result) {
                response.sendError(500);
            }
        } else {
            response.sendError(403);
        }
    } else if (uriMatcher.match("{context}/api/devices/{type}/{deviceId}/{operation}")) {
        elements = uriMatcher.elements();
        deviceId = elements.deviceId;
        type = elements.type;
        operation = elements.operation;
        if (userModule.isAuthorized("/permission/admin/device-mgt/devices/operation")) {
            result = deviceModule.performOperation(deviceId, operation, [], type);
        } else {
            response.sendError(403);
        }
    }
}

// Returning the result.
if (result) {
    print(result);
}

%>