/*
 * 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.
 */

function onRequest(context) {
    var deviceType = context["uriParams"]["deviceType"];
    var deviceId = request.getParameter("id");
    var owner = request.getParameter("owner");
    var deviceViewData = {};
    var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"];

    var DeviceManagementProviderServiceImpl =
        Packages.org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
    var deviceManagementProviderServiceImpl = new DeviceManagementProviderServiceImpl();

    if (deviceType && deviceId) {
        var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
        var response = deviceModule.viewDevice(deviceType, deviceId, owner);
        if (response["status"] == "success") {
            deviceViewData["deviceFound"] = true;
            deviceViewData["isAuthorized"] = true;

            var filteredDeviceData = response["content"];
            // creating deviceView information model from filtered device data
            var viewModel = {};
            viewModel["isEnable"] = false;
            viewModel["isLocationEnable"] = false;
            viewModel["isDeviceInfoEnable"] = false;

            if (deviceManagementProviderServiceImpl.isDeviceMonitoringEnabled("ios")) {
                viewModel["isEnable"] = true;
                var deviceMonitoringTasks = deviceManagementProviderServiceImpl.getMonitoringOperationList("ios");
                if (deviceMonitoringTasks) {
                    for (var index = 0; index < deviceMonitoringTasks.size(); index++) {
                        if (String(deviceMonitoringTasks.get(index).getTaskName()) === "DEVICE_INFO") {
                            viewModel["isDeviceInfoEnable"] = true;
                        }
                        else if (String(deviceMonitoringTasks.get(index).getTaskName()) === "DEVICE_LOCATION") {
                            viewModel["isLocationEnable"] = true;
                        }
                    }
                }
            }
            if (filteredDeviceData["type"]) {
                viewModel["type"] = filteredDeviceData["type"];
                viewModel.isNotWindows = true;
            }
            if (filteredDeviceData["deviceIdentifier"]) {
                viewModel["deviceIdentifier"] = filteredDeviceData["deviceIdentifier"];
            }
            if (filteredDeviceData["name"]) {
                viewModel["name"] = filteredDeviceData["name"];
            }
            if (filteredDeviceData["enrolmentInfo"]) {
                if (filteredDeviceData["enrolmentInfo"]["status"]) {
                    viewModel["status"] = filteredDeviceData["enrolmentInfo"]["status"];
                    viewModel.isActive = false ;
                    viewModel.isNotRemoved = true;
                    if (filteredDeviceData["enrolmentInfo"]["status"]== "ACTIVE") {
                        viewModel.isActive = true ;
                    }
                    if (filteredDeviceData["enrolmentInfo"]["status"]== "REMOVED") {
                        viewModel.isNotRemoved = false ;
                    }
                }
                if (filteredDeviceData["enrolmentInfo"]["owner"]) {
                    viewModel["owner"] = filteredDeviceData["enrolmentInfo"]["owner"];
                }
                if (filteredDeviceData["enrolmentInfo"]["ownership"]) {
                    viewModel["ownership"] = filteredDeviceData["enrolmentInfo"]["ownership"];
                }
            }
            if (filteredDeviceData["initialDeviceInfo"]) {
                viewModel["deviceInfoAvailable"] = true;
                var initialDeviceInfo = filteredDeviceData["initialDeviceInfo"];
                if (initialDeviceInfo["IMEI"]) {
                    viewModel["imei"] = initialDeviceInfo["IMEI"];
                }
                if (initialDeviceInfo["OS_BUILD_DATE"]) {
                    if (initialDeviceInfo["OS_BUILD_DATE"] != "0") {
                        viewModel["osBuildDate"] = new Date(initialDeviceInfo["OS_BUILD_DATE"] * 1000);
                    }
                }
                if (initialDeviceInfo["LATITUDE"] && initialDeviceInfo["LONGITUDE"]) {
                    viewModel["location"] = {};
                    viewModel["location"]["latitude"] = initialDeviceInfo["LATITUDE"];
                    viewModel["location"]["longitude"] = initialDeviceInfo["LONGITUDE"];
                }
                if (initialDeviceInfo["VENDOR"] && initialDeviceInfo["DEVICE_MODEL"]) {
                    viewModel["vendor"] = initialDeviceInfo["VENDOR"];
                    viewModel["model"] = initialDeviceInfo["DEVICE_MODEL"];
                }
                if (initialDeviceInfo["DEVICE_INFO"]) {
                    var deviceInfo = initialDeviceInfo["DEVICE_INFO"];
                    viewModel["LastCloudBackupDate"] = deviceInfo["LastCloudBackupDate"];
                    if (deviceInfo["OSVersion"]) {
                        viewModel["osVersion"] = deviceInfo["OSVersion"];
                    }
                    viewModel["BatteryLevel"] = {};
                    viewModel["BatteryLevel"]["value"] = replaceNaNVal(Math.round(deviceInfo["BatteryLevel"] * 10000) / 100);

                    viewModel["internalMemory"] = {};
                    viewModel["internalMemory"]["total"] = replaceNaNVal(Math.
                                                                             round(deviceInfo["DeviceCapacity"] * 100) / 100);
                    if (deviceInfo["DeviceCapacity"] != 0) {
                        viewModel["internalMemory"]["usage"] = replaceNaNVal(Math.round(deviceInfo["DeviceCapacity"] -
                                                                                        deviceInfo["AvailableDeviceCapacity"]));
                    } else {
                        viewModel["internalMemory"]["usage"] = 0;
                    }
                    if(deviceInfo["VENDOR"]) {
                        viewModel["vendor"] = deviceInfo["VENDOR"];
                    }
                    if(deviceInfo["Model"]) {
                        viewModel["model"] = deviceInfo["Model"];
                    }
                }
            }
            if (filteredDeviceData["latestDeviceInfo"]) {
                viewModel["deviceInfoAvailable"] = true;
                var latestDeviceData = filteredDeviceData["latestDeviceInfo"];
                if (latestDeviceData["osBuildDate"]) {
                    if (latestDeviceData["osBuildDate"] != "0") {
                        viewModel["osBuildDate"] = new Date(latestDeviceData["osBuildDate"] * 1000);
                    }
                }
                if (latestDeviceData["location"]["latitude"] &&
                    latestDeviceData["location"]["longitude"]) {
                    viewModel["location"] = {};
                    viewModel["location"]["latitude"] = latestDeviceData["location"]["latitude"];
                    viewModel["location"]["longitude"] = latestDeviceData["location"]["longitude"];
                    viewModel["location"]["updatedTime"] = latestDeviceData["location"]["updatedTime"];
                }
                if (latestDeviceData["vendor"] && latestDeviceData["deviceModel"]) {
                    viewModel["vendor"] = latestDeviceData["vendor"];
                    viewModel["model"] = latestDeviceData["deviceModel"];
                }
                if (latestDeviceData["updatedTime"]) {
                    viewModel["lastUpdatedTime"] = latestDeviceData["updatedTime"].
                    substr(0, latestDeviceData["updatedTime"].indexOf("+"));
                }
                if (latestDeviceData["batteryLevel"]) {
                    viewModel["BatteryLevel"] = {};
                    viewModel["BatteryLevel"]["value"] = latestDeviceData["batteryLevel"];
                }
                if (latestDeviceData["cpuUsage"]) {
                    viewModel["cpuUsage"] = {};
                    viewModel["cpuUsage"]["value"] = latestDeviceData["cpuUsage"];
                }

                if (latestDeviceData["totalRAMMemory"]) {
                    viewModel["ramUsage"] = {};
                    if (latestDeviceData["totalRAMMemory"] != 0) {
                        viewModel["ramUsage"]["value"] = replaceNaNVal(Math.
                        round((latestDeviceData["totalRAMMemory"] -
                               latestDeviceData["availableRAMMemory"])
                              / latestDeviceData["totalRAMMemory"] * 10000) / 100);
                    } else {
                        viewModel["ramUsage"]["value"] = 0;
                    }
                }

                if (latestDeviceData["internalTotalMemory"]) {
                    viewModel["internalMemory"] = {};
                    if (latestDeviceData["internalTotalMemory"] != 0) {
                        viewModel["internalMemory"]["total"] = replaceNaNVal(Math.round
                        (latestDeviceData["internalTotalMemory"] * 100) / 100);
                        viewModel["internalMemory"]["usage"] = replaceNaNVal(Math.round
                        (latestDeviceData["internalAvailableMemory"]* 100) / 100);
                    } else {
                        viewModel["internalMemory"]["usage"] = 0;
                    }
                }

                if (latestDeviceData["externalTotalMemory"]) {
                    viewModel["externalMemory"] = {};
                    if (latestDeviceData["externalTotalMemory"] != 0) {
                        viewModel["externalMemory"]["total"] = replaceNaNVal(Math.
                                        round(latestDeviceData["externalTotalMemory"] * 100) / 100);
                        viewModel["externalMemory"]["usage"] = replaceNaNVal(Math.
                                         round((latestDeviceData["externalTotalMemory"] -
                                               latestDeviceData["externalAvailableMemory"])
                                               / latestDeviceData["externalTotalMemory"] * 10000) / 100);
                    } else {
                        viewModel["externalMemory"]["usage"] = 0;
                    }
                }
            }
            if (!filteredDeviceData["initialDeviceInfo"] && !filteredDeviceData["latestDeviceInfo"]) {
                viewModel["deviceInfoAvailable"] = false;
            }
            viewModel.locationHistory = stringify(filteredDeviceData["locationHistory"]);
            deviceViewData["device"] = viewModel;
        } else if (response["status"] == "unauthorized") {
            deviceViewData["deviceFound"] = true;
            deviceViewData["isAuthorized"] = false;
        } else if (response["status"] == "notFound") {
            deviceViewData["deviceFound"] = false;
        }
    } else {
        deviceViewData["deviceFound"] = false;
    }

    var autoCompleteParams = [
        {"name" : "deviceId", "value" : deviceId}
    ];

    deviceViewData["autoCompleteParams"] = autoCompleteParams;
    deviceViewData["isCloud"] = deviceMgtProps['isCloud'];
    return deviceViewData;

    function replaceNaNVal(val) {
        if (isNaN(val)) {
            return "N/A";
        }
        return val;
    }
}