<%
/*
 * Copyright (c) 2015, 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/operation-api.jag");

var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];

if (uriMatcher.match("/{context}/api/operation/paginate")) {
    var deviceType = request.getParameter("deviceType");
    var deviceId = request.getParameter("deviceId");
    var owner = request.getParameter("owner");
    var index = request.getParameter("start");
    var length = request.getParameter("length");
    var search = request.getParameter("search[value]");

    var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
        "/devices/" + deviceType + "/" + deviceId + "/operations?owner=" + owner + "&offset=" + index + "&limit=" + length;

    serviceInvokers.XMLHttp.get(
        restAPIEndpoint,
        function (restAPIResponse) {
            if (restAPIResponse["status"] == 200 && restAPIResponse["responseText"]) {
                var responsePayload = parse(restAPIResponse["responseText"]);

                var paginatedResult = {};
                paginatedResult["recordsTotal"] = responsePayload["count"];
                paginatedResult["recordsFiltered"] = responsePayload["count"];
                paginatedResult["data"] = responsePayload["operations"];

                response["status"] = restAPIResponse["status"];
                response["content"] = paginatedResult;
            } else {
                response["status"] = restAPIResponse["status"];
                if (restAPIResponse["responseText"]) {
                    var responseText = "";
                    try {
                        response["content"] =  parse(restAPIResponse["responseText"]);
                    } catch (e) {
                        responseText = restAPIResponse["responseText"];
                    }
                }
            }
        }
    );
}
%>