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

/**
 * Checks if provided input is valid against RegEx input.
 *
 * @param regExp Regular expression
 * @param inputString Input string to check
 * @returns {boolean} Returns true if input matches RegEx
 */
function inputIsValid(regExp, inputString) {
    return regExp.test(inputString);
}

/**
 * Checks if provided input is valid against RegEx input.
 *
 * @param regExp Regular expression
 * @param inputString Input string to check
 * @returns {boolean} Returns true if input matches RegEx
 */
function isPositiveInteger(str) {
    return /^\+?(0|[1-9]\d*)$/.test(str);
}

/**
 * Get valid param.
 *
 * @param  certificate
 * @param cached param (in the registry)
 * @returns {String} Returns the valid param
 */
function validateCertificateParams(param, cachedParam) {
    if (param == '' && cachedParam != null) {
        return cachedParam;
    } else {
        return param;
    }
}

/**
 * Checks if an email address has the valid format or not.
 *
 * @param email Email address
 * @returns {boolean} true if email has the valid format, otherwise false.
 */
function emailIsValid(email) {
    var regExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return regExp.test(email);
}

var iOSMDMCertificateName = null;
var iOSMDMCertificate = null;
var iOSAPNSCertificateName = null;
var iOSAPNSCertificate = null;

var notifierTypeConstants = {
    "LOCAL": "1",
    "GCM": "2"
};
// Constants to define platform types available
var platformTypeConstants = {
    "IOS": "ios"
};

var responseCodes = {
    "CREATED": "Created",
    "SUCCESS": "201",
    "INTERNAL_SERVER_ERROR": "Internal Server Error"
};

var configParams = {
    "NOTIFIER_TYPE": "notifierType",
    "NOTIFIER_FREQUENCY": "notifierFrequency",
    "GCM_API_KEY": "gcmAPIKey",
    "GCM_SENDER_ID": "gcmSenderId",
    "IOS_EULA": "iosEula",
    "CONFIG_COUNTRY": "configCountry",
    "CONFIG_STATE": "configState",
    "CONFIG_LOCALITY": "configLocality",
    "CONFIG_ORGANIZATION": "configOrganization",
    "CONFIG_ORGANIZATION_UNIT": "configOrganizationUnit",
    "MDM_CERT_PASSWORD": "MDMCertPassword",
    "MDM_CERT_TOPIC_ID": "MDMCertTopicID",
    "APNS_CERT_PASSWORD": "APNSCertPassword",
    "MDM_CERT": "MDMCert",
    "MDM_CERT_NAME": "MDMCertName",
    "APNS_CERT": "APNSCert",
    "APNS_CERT_NAME": "APNSCertName",
    "ORG_DISPLAY_NAME": "organizationDisplayName",
    "GENERAL_EMAIL_HOST": "emailHost",
    "GENERAL_EMAIL_PORT": "emailPort",
    "GENERAL_EMAIL_USERNAME": "emailUsername",
    "GENERAL_EMAIL_PASSWORD": "emailPassword",
    "GENERAL_EMAIL_SENDER_ADDRESS": "emailSender",
    "GENERAL_EMAIL_TEMPLATE": "emailTemplate",
    "COMMON_NAME": "commonName",
    "KEYSTORE_PASSWORD": "keystorePassword",
    "PRIVATE_KEY_PASSWORD": "privateKeyPassword",
    "BEFORE_EXPIRE": "beforeExpire",
    "AFTER_EXPIRE": "afterExpire",
    "WINDOWS_EULA": "windowsLicense",
    "IOS_CONFIG_MDM_MODE": "iOSConfigMDMMode",
    "IOS_CONFIG_APNS_MODE": "iOSConfigAPNSMode"
};

function promptErrorPolicyPlatform(errorMsg) {
    var mainErrorMsgWrapper = "#platform-config-main-error-msg";
    var mainErrorMsg = mainErrorMsgWrapper + " span";
    $(mainErrorMsg).text(errorMsg);
    $(mainErrorMsgWrapper).show();
}

$(document).ready(function () {

    $("#gcm-inputs").hide();
    tinymce.init({
                     selector: "textarea",
                     height: 500,
                     theme: "modern",
                     plugins: [
                         "autoresize",
                         "advlist autolink lists link image charmap print preview anchor",
                         "searchreplace visualblocks code fullscreen",
                         "insertdatetime image table contextmenu paste"
                     ],
                     toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
                 });

    var iosConfigAPI = "/api/device-mgt/ios/v1.0/configuration";

    invokerUtil.get(
        iosConfigAPI,
        function (data) {
            data = JSON.parse(data);
            if (data != null && data.configuration != null) {
                for (var i = 0; i < data.configuration.length; i++) {
                    var config = data.configuration[i];
                    if (config.name == configParams["CONFIG_COUNTRY"]) {
                        $("input#ios-config-country").val(config.value);
                    } else if (config.name == configParams["CONFIG_STATE"]) {
                        $("input#ios-config-state").val(config.value);
                    } else if (config.name == configParams["CONFIG_LOCALITY"]) {
                        $("input#ios-config-locality").val(config.value);
                    } else if (config.name == configParams["CONFIG_ORGANIZATION"]) {
                        $("input#ios-config-organization").val(config.value);
                    } else if (config.name == configParams["CONFIG_ORGANIZATION_UNIT"]) {
                        $("input#ios-config-organization-unit").val(config.value);
                    } else if (config.name == configParams["MDM_CERT_PASSWORD"]) {
                        $("input#ios-config-mdm-certificate-password").val(config.value);
                    } else if (config.name == configParams["MDM_CERT_TOPIC_ID"]) {
                        $("input#ios-config-mdm-certificate-topic-id").val(config.value);
                    } else if (config.name == configParams["APNS_CERT_PASSWORD"]) {
                        $("input#ios-config-apns-certificate-password").val(config.value);
                    } else if (config.name == configParams["MDM_CERT_NAME"]) {
                        $("#mdm-cert-file-name").html(config.value);
                        iOSMDMCertificateName = config.value;
                    } else if (config.name == configParams["MDM_CERT"]) {
                        iOSMDMCertificate = config.value;
                    } else if (config.name == configParams["APNS_CERT_NAME"]) {
                        $("#apns-cert-file-name").html(config.value);
                        iOSAPNSCertificateName = config.value;
                    } else if (config.name == configParams["APNS_CERT"]) {
                        iOSAPNSCertificate = config.value;
                    } else if (config.name == configParams["ORG_DISPLAY_NAME"]) {
                        $("input#ios-org-display-name").val(config.value);
                    } else if (config.name == configParams["IOS_EULA"]) {
                        $("#ios-eula").val(config.value);
                    } else if (config.name == configParams["IOS_CONFIG_MDM_MODE"]) {
                        if (config.value == 2) {
                            $('#ios-config-mdm-mode option:eq(1)').prop('selected', true);
                        } else {
                            $('#ios-config-mdm-mode option:eq(0)').prop('selected', true);
                        }
                    } else if (config.name == configParams["IOS_CONFIG_APNS_MODE"]) {
                        if (config.value == 2) {
                            $('#ios-config-apns-mode option:eq(1)').prop('selected', true);
                        } else {
                            $('#ios-config-apns-mode option:eq(0)').prop('selected', true);
                        }
                    }
                }
            }
        }, function (data) {
            console.log(data);
        }
    );

    $("select.select2[multiple=multiple]").select2({
                                                       tags: true
                                                   });

    var errorMsgWrapper = "#ios-config-error-msg";
    var errorMsg = "#ios-config-error-msg span";
    var fileTypes = ['pfx'];
    var notSupportedError = false;

    var base64MDMCert = "";
    var fileInputMDMCert = $('#ios-config-mdm-certificate');
    var fileNameMDMCert = "";
    var invalidFormatMDMCert = false;

    var base64APNSCert = "";
    var fileInputAPNSCert = $('#ios-config-apns-certificate');
    var fileNameAPNSCert = "";
    var invalidFormatAPNSCert = false;

    $(fileInputMDMCert).change(function () {

        if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
            $(errorMsg).text("The File APIs are not fully supported in this browser.");
            $(errorMsgWrapper).removeClass("hidden");
            notSupportedError = true;
            return;
        }

        var file = fileInputMDMCert[0].files[0];
        fileNameMDMCert = file.name;
        var extension = file.name.split('.').pop().toLowerCase(),
            isSuccess = fileTypes.indexOf(extension) > -1;

        if (isSuccess) {
            var fileReader = new FileReader();
            fileReader.onload = function (event) {
                base64MDMCert = event.target.result;
            };
            fileReader.readAsDataURL(file);
            invalidFormatMDMCert = false;
        } else {
            base64MDMCert = "";
            invalidFormatMDMCert = true;
        }
    });

    $(fileInputAPNSCert).change(function () {

        if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
            $(errorMsg).text("The File APIs are not fully supported in this browser.");
            $(errorMsgWrapper).removeClass("hidden");
            notSupportedError = true;
            return;
        }

        var file = fileInputAPNSCert[0].files[0];
        fileNameAPNSCert = file.name;
        var extension = file.name.split('.').pop().toLowerCase(),
            isSuccess = fileTypes.indexOf(extension) > -1;

        if (isSuccess) {
            var fileReader = new FileReader();
            fileReader.onload = function (event) {
                base64APNSCert = event.target.result;
            };
            fileReader.readAsDataURL(file);
            invalidFormatAPNSCert = false;
        } else {
            base64APNSCert = "";
            invalidFormatAPNSCert = true;
        }
    });

    $("button#save-ios-btn").click(function () {
        var configCountry = $("#ios-config-country").val();
        var configState = $("#ios-config-state").val();
        var configLocality = $("#ios-config-locality").val();
        var configOrganization = $("#ios-config-organization").val();
        var configOrganizationUnit = $("#ios-config-organization-unit").val();
        var MDMCertPassword = $("#ios-config-mdm-certificate-password").val();
        var MDMCertTopicID = $("#ios-config-mdm-certificate-topic-id").val();
        var APNSCertPassword = $("#ios-config-apns-certificate-password").val();
        var configOrgDisplayName = $("#ios-org-display-name").val();
        var iosLicense = tinyMCE.activeEditor.getContent();
        var iOSConfigMDMMode = $("#ios-config-mdm-mode").val();
        var iOSConfigAPNSMode = $("#ios-config-apns-mode").val();

        fileNameMDMCert = validateCertificateParams(fileNameMDMCert, iOSMDMCertificateName);
        fileNameAPNSCert = validateCertificateParams(fileNameAPNSCert, iOSAPNSCertificateName);
        base64MDMCert = validateCertificateParams(base64MDMCert, iOSMDMCertificate);
        base64APNSCert = validateCertificateParams(base64APNSCert, iOSAPNSCertificate);

        if (!configCountry) {
            $(errorMsg).text("SCEP country is a required field. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (!configState) {
            $(errorMsg).text("SCEP state is a required field. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (!configLocality) {
            $(errorMsg).text("SCEP locality is a required field. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (!configOrganization) {
            $(errorMsg).text("SCEP organization is a required field. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (!configOrganizationUnit) {
            $(errorMsg).text("SCEP organization unit is a required field. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (!MDMCertPassword) {
            $(errorMsg).text("MDM certificate password is a required field. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (!MDMCertTopicID) {
            $(errorMsg).text("MDM certificate topic ID is a required field. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (notSupportedError) {
            $(errorMsg).text("The File APIs are not fully supported in this browser.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (invalidFormatMDMCert) {
            $(errorMsg).text("MDM certificate needs to be in pfx format.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (base64MDMCert == '') {
            $(errorMsg).text("MDM certificate is a required field. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (invalidFormatAPNSCert && base64APNSCert != '') {
            $(errorMsg).text("APNS certificate needs to be in pfx format.");
            $(errorMsgWrapper).removeClass("hidden");
        } else if (!configOrgDisplayName) {
            $(errorMsg).text("Organization display name is a required field. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else {
            var addConfigFormData = {};
            var configList = new Array();

            var configCountry = {
                "name": configParams["CONFIG_COUNTRY"],
                "value": configCountry,
                "contentType": "text"
            };

            var configState = {
                "name": configParams["CONFIG_STATE"],
                "value": configState,
                "contentType": "text"
            };

            var configLocality = {
                "name": configParams["CONFIG_LOCALITY"],
                "value": configLocality,
                "contentType": "text"
            };

            var configOrganization = {
                "name": configParams["CONFIG_ORGANIZATION"],
                "value": configOrganization,
                "contentType": "text"
            };

            var configOrganizationUnit = {
                "name": configParams["CONFIG_ORGANIZATION_UNIT"],
                "value": configOrganizationUnit,
                "contentType": "text"
            };

            var MDMCertPassword = {
                "name": configParams["MDM_CERT_PASSWORD"],
                "value": MDMCertPassword,
                "contentType": "text"
            };

            var MDMCertTopicID = {
                "name": configParams["MDM_CERT_TOPIC_ID"],
                "value": MDMCertTopicID,
                "contentType": "text"
            };

            var APNSCertPassword = {
                "name": configParams["APNS_CERT_PASSWORD"],
                "value": APNSCertPassword,
                "contentType": "text"
            };

            var paramBase64MDMCert = {
                "name": configParams["MDM_CERT"],
                "value": base64MDMCert,
                "contentType": "text"
            };

            var MDMCertName = {
                "name": configParams["MDM_CERT_NAME"],
                "value": fileNameMDMCert,
                "contentType": "text"
            };

            var paramBase64APNSCert = {
                "name": configParams["APNS_CERT"],
                "value": base64APNSCert,
                "contentType": "text"
            };

            var APNSCertName = {
                "name": configParams["APNS_CERT_NAME"],
                "value": fileNameAPNSCert,
                "contentType": "text"
            };

            var paramOrganizationDisplayName = {
                "name": configParams["ORG_DISPLAY_NAME"],
                "value": configOrgDisplayName,
                "contentType": "text"
            };

            var iosEula = {
                "name": configParams["IOS_EULA"],
                "value": iosLicense,
                "contentType": "text"
            };

            var iosMDMMode = {
                "name": configParams["IOS_CONFIG_MDM_MODE"],
                "value": iOSConfigMDMMode,
                "contentType": "text"
            };

            var iosAPNSMode = {
                "name": configParams["IOS_CONFIG_APNS_MODE"],
                "value": iOSConfigAPNSMode,
                "contentType": "text"
            };

            configList.push(configCountry);
            configList.push(configState);
            configList.push(configLocality);
            configList.push(configOrganization);
            configList.push(configOrganizationUnit);
            configList.push(MDMCertPassword);
            configList.push(MDMCertTopicID);
            configList.push(APNSCertPassword);
            configList.push(paramBase64MDMCert);
            configList.push(MDMCertName);
            configList.push(paramBase64APNSCert);
            configList.push(APNSCertName);
            configList.push(paramOrganizationDisplayName);
            configList.push(iosEula);
            configList.push(iosMDMMode);
            configList.push(iosAPNSMode);

            addConfigFormData.type = platformTypeConstants["IOS"];
            addConfigFormData.configuration = configList;

            var addConfigAPI = iosConfigAPI;
            invokerUtil.put(
                addConfigAPI,
                addConfigFormData,
                function (data, textStatus, jqXHR) {
                    data = JSON.parse(data);
                    if (jqXHR.status == 200) {
                        $("#config-save-form").addClass("hidden");
                        $("#record-created-msg").removeClass("hidden");
                    }
                    $(errorMsgWrapper).removeClass("hidden");
                }, function (data) {
                    data = data.status;
                    if (data == 500) {
                        $(errorMsg).text("Exception occurred at backend.");
                    } else if (data == 403) {
                        $(errorMsg).text("Action was not permitted.");
                    } else {
                        $(errorMsg).text("An unexpected error occurred.");
                    }
                    $(errorMsgWrapper).removeClass("hidden");
                }
            );
        }

    });

});
