var isPasswordsValid = true;
var isShareValid = true;
var isUserValid = true;
var isEmailPasswordsValid = true;
var emailResponse;
connectionParameters = [
    {
        connectionType: "ethernet",
        url: "../cgi/cgi_IpCfgManager.py",
        data: {
            requestType: "read_IP"
        }
    },
    {
        connectionType: "serial",
        url: "../cgi/cgi_SerialManager.py",
        data: {
            requestType: "read_serial"
        }
    },
    {
        connectionType: "remote",
        url: "../cgi/cgi_RemoteControl.py",
        data: {
            requestType: "read_remote_control"
        }
    },
    {
        connectionType: "email",
        url: "../cgi/cgi_EmailManager.py",
        data: {
            requestType: "read_email"
        }
    },
    {
        connectionType: "remote_storage",
        url: "../cgi/cgi_RemoteStorageManager.py",
        data: {
            requestType: "read_remoteStorage"
        }
    },
    {
        connectionType: "Password_hidden",
        url: "../cgi/cgi_RemoteStorageManager.py",
        data: {
            requestType: "read_passwordHidden"
        }
    },
    {
        connectionType: "read_enable_ssh",
        url: "../cgi/cgi_EnableSsh.py",
        data: {
            requestType: "read_enable_ssh"
        }
    },
    {
        connectionType: "read_reverse_ssh",
        url: "../cgi/cgi_EnableSsh.py",
        data: {
            requestType: "read_reverse_ssh"
        }
    }
];

function readConnectionData() {
    connectionParameters.forEach(function (parameter) {
        $.ajax({
            type: "Get",
            url: parameter.url,
            contentType: 'application/json',
            dataType: 'json',
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            data: parameter.data,
            success: function (response) {
                readJsonData(parameter.connectionType, response);
            },
            error: function (ex) {
                console.log(ex);
            }
        });
    });
}

function configureConnectionSettings(connectionType) {
    if (isCllicked == false) {
        isCllicked = true;
        switch (connectionType) {
            case "ethernet":
                parameters = {
                    requestType: "create_IP",
                    ip_addr: $("#IPaddress").val(),
                    netmask: $("#subNetMask").val(),
                    gateway: $("#defaultGetway").val(),
                    dns: $("#DNSServer").val(),
                    enabled: $('#ethernetCheckButton').prop('checked') == true ? 1 : 0
                };
                if (validateIPAddress(parameters.ip_addr) && validateIPAddress(parameters.netmask) && validateIPAddress(parameters.gateway) && validateIPAddress(parameters.dns)) {
                    url = '../cgi/cgi_IpCfgManager.py';
                } else {
                    alert("Please check Ethernet Details!")
                    isCllicked = false;
                    return;
                }

                saveConnectionSettings(connectionType);
                break;
            case "serial":
                parameters = {
                    requestType: "create_serial",
                    baud_rate: $("#BAUDRate").val(),
                    parity: $("#Parity").val(),
                    data_bits: $("#DataBits").val(),
                    flow_control: $("#flowControl").val(),
                    enabled: $('#serialCheckButton').prop('checked') == true ? 1 : 0
                };
                url = '../cgi/cgi_SerialManager.py';
                saveConnectionSettings(connectionType);
                break;
            case "remote_storage":
                parameters = {
                    requestType: "create_remoteStorage",
                    share: $("#rs-share").val(),
                    user: $("#rs-user").val(),
                    password: $("#rs-password").val(),
                    protocol: $("#protocol").val(),
                    enabled: $('#remoteButton').prop('checked') == true ? 1 : 0
                };
                url = '../cgi/cgi_RemoteStorageManager.py';
                saveConnectionSettings(connectionType);
                break;
            case "remote":
                parameters = {
                    requestType: 'create_remote_control',
                    id: parseInt($("#remoteControlID").val()),
                    enabled: $('#remoteControlEnable').prop('checked') == true ? 1 : 0
                };
                url = '../cgi/cgi_RemoteControl.py';
                saveConnectionSettings(connectionType);
                break;
            case "enableSsh":
                parameters = {
                    requestType: 'udpate_enable_ssh',
                    type: $("input[name='rbEnSSH']:checked").val(),
                    enabled : $('#sshButton').prop('checked') == true ? 1 : 0             
                };
                url = '../cgi/cgi_EnableSsh.py';
                saveConnectionSettings(connectionType);
                break;
            case "reverseSsh":
                let enable_reverse =  $("input[name='enReverseSSH']:checked").val();
                let formData = new FormData();
                formData.append('requestType', 'udpate_reverse_ssh');
                formData.append('enable_reverse', enable_reverse);
                formData.append('rev_enabled', $('#reverseSsh').prop('checked') ? 1 : 0);
                formData.append('rs_remote_ip', $("#rs_remote_ip").val());
                formData.append('rs_remote_port', $("#rs_remote_port").val());
                formData.append('rs_remote_user', $("#rs_remote_user").val());
                formData.append('rs_local_port', $("#rs_local_port").val());
                let fileInput = $('#rs_key_path')[0];
                let fileExist = $("#key_file_name").text();
                if (enable_reverse == "yes"){
                    if (!fileExist){
                        if (fileInput.files.length > 0) {
                            formData.append('rs_key_file', fileInput.files[0]);
                        } else {
                            alert("Please select a private key file");
                            return;
                        }
                    }
                    else{
                        if (fileInput.files.length > 0) {
                            formData.append('rs_key_file', fileInput.files[0]);
                        }
                        else{
                            formData.append('rs_key_file_name', fileExist);
                        }
                    }
                }
                else{
                    formData.append('rs_key_file_name', fileExist);
                }

                url = '../cgi/cgi_EnableSsh.py';
                isCllicked = false;
                saveReverseSSHData(url,formData)
                break;
        }
    }
}

function saveConnectionSettings(connectionType) {
    $('.loaderDiv').css('display', 'block');
    $.ajax({
        type: "get",
        url: url,
        contentType: 'application/json',
        dataType: 'json',
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: parameters,
        success: function (response) {
            $('.loaderDiv').css('display', 'none');
            if (response.status == "fail") {
                $(".modal-header").css({
                    "color": "#fff",
                    "background-color": "#db4141"
                });
                $(".close").css({
                    "color": "#fff"
                });
                mymodal.find('.modal-title').text('Error');
                mymodal.find('.modal-body').text(response.description).css({ "text-align": "center" });
                if (connectionType == 'email') {
                    $(".modal-header").css({
                        "color": "#fff",
                        "background-color": "#db4141"
                    });
                    $(".close").css({
                        "color": "#fff"
                    });
                    setTimeout(() => {
                        if (response?.type == 'invalid') {
                            $("#senderEmail").val(emailResponse[0]?.in_server);
                            $("#password").val(emailResponse[0]?.pw);
                            $('#setUpEmailModel').modal('show');
                        }
                        else {
                            $("#portNumber").val(emailResponse[0]?.port_number)
                            $('#setUpEmailModel').modal('show');
                        }
                        $(".modal-header").css({
                            "color": "#000",
                            "background-color": "#fff"
                        });
                        $(".close").css({
                            "color": "#000"
                        });
                    }, autoClose)
                }
            } else {
                switch (connectionType) {
                    case "ethernet":
                        mymodal.find('.modal-title').text('Ethernet');
                        mymodal.find('.modal-body').text('Ethernet details has been updated successfully');
                        break;
                    case "serial":
                        mymodal.find('.modal-title').text('Serial');
                        mymodal.find('.modal-body').text('Serial details has been updated successfully');
                        break;
                    case "remote_storage":
                        mymodal.find('.modal-title').text('Remote Storage');
                        mymodal.find('.modal-body').text('Remote Storage details has been updated successfully');
                        break;
                    case "remote":
                        mymodal.find('.modal-title').text('Remote Control');
                        mymodal.find('.modal-body').text('Remote Control has been updated successfully');
                        break;
                    case "email":
                        mymodal.find('.modal-title').text('Email');
                        mymodal.find('.modal-body').text('Email details has been updated successfully');
                        break;
                    case "enableSsh":
                        mymodal.find('.modal-title').text('Enable SSH');
                        mymodal.find('.modal-body').text('Enable SSh details has been updated successfully');
                        break;
                    case "reverseSsh":
                        mymodal.find('.modal-title').text('Reverse SSH');
                        mymodal.find('.modal-body').text('Enable Reverse SSh details has been updated successfully');
                        break;
                }
            }
            mymodal.modal('show');
            setTimeout(() => {
                mymodal.modal("hide");
                $(".modal-header").css({
                    "color": "#000",
                    "background-color": "#fff"
                });
                $(".close").css({
                    "color": "#000"
                });
            }, autoClose)
            isCllicked = false;
            isSetUnprotectedMode = false;
        },
        error: function (ex) {
            isCllicked = false;
            $('#test').html(ex.responseText);
        }
    });
}

function validateIPAddress(idAddress) {
    var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    if (idAddress.match(ipformat)) {
        return true;
    } else {
        // alert("You have entered an invalid IP address!");
        return false;
    }
}

function configureEmail() {
    if (isCllicked == false) {
        isCllicked == true;
        parameters = {
            requestType: "create_email",
            name: "email",
            id: 1,
            out_server: $("#recipientEmail").val(),
            in_server: $("#senderEmail").val(),
            authentication: $('#authenticationCheck').prop('checked') == true ? true : false,
            pw: $("#password").val(),
            smtp_server: $("#smtpServer").val(),
            port_number: $("#portNumber").val(),
            alert_msg: $('#alertMessagesON').prop('checked') == true ? true : false,
            level: ""
        }

        if ($('#alertMessagesON').prop('checked') == true) {
            $.each($("input[name='alertMessages']:checked"), function () {
                parameters.level = parameters.level + "," + $(this).val();
            });
        } else {
            parameters.level = "";
        }

        if (parameters.level == "" && $('#alertMessagesON').prop('checked') == true) {
            $(".modal-header").css({
                "color": "#fff",
                "background-color": "#db4141"
            });
            $(".close").css({
                "color": "#fff"
            });
            showModal('Email Error', "Atleast one level should be selected");
            return false;
        }

        if (validateEmail(parameters.out_server, parameters.in_server)) {
            url = '../cgi/cgi_EmailManager.py';
            saveConnectionSettings("email");
        } else {
            isCllicked = false;
        }

    }

};

function validateEmail(recipient_email, sender_email) {
    var rEmail = recipient_email.split(",");
    var isValidrEmail = true;
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(sender_email)) {
        rEmail.forEach(function (email_id) {
            if (isValidrEmail) {
                if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email_id.trim())) {
                    isValidrEmail = true;
                } else {
                    isValidrEmail = false;
                }
            }
        });
        if (isValidrEmail)
            return true;
        else {
            showModal('Email Error', "You have entered an invalid Recipient  email address!");
            return false;
        }
    } else {
        showModal('Email Error', "You have entered an invalid Sender  email address!");
        return false;
    }
};
function checkValidation() {
    var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    $("#IPaddress").keyup(function (eve) {
        if (eve.target.value.match(ipformat)) {
            $("#IPaddress").removeClass("is-invalid");
            $("#ipaddress-error").html("")
        }
        else {
            $("#IPaddress").addClass("is-invalid");
            $("#ipaddress-error").html("Invalid IP Address")

        }
    })
    $("#subNetMask").keyup(function (eve) {
        if (eve.target.value.match(ipformat)) {
            $("#subNetMask").removeClass("is-invalid");
            $("#subnet-error").html("")
        }
        else {
            $("#subNetMask").addClass("is-invalid");
            $("#subnet-error").html("Invalid SubNet Mask")
        }
    })
    $("#defaultGetway").keyup(function (eve) {
        if (eve.target.value.match(ipformat)) {
            $("#defaultGetway").removeClass("is-invalid");
            $("#default-error").html("")

        }
        else {
            $("#defaultGetway").addClass("is-invalid");
            $("#default-error").html("Invalid Default Gateway")
        }
    })
    $("#DNSServer").keyup(function (eve) {
        if (eve.target.value.match(ipformat)) {
            $("#DNSServer").removeClass("is-invalid");
            $("#dns-error").html("")
        }
        else {
            $("#DNSServer").addClass("is-invalid");
            $("#dns-error").html("Invalid DNS Server")
        }
    })
}

$(document).ready(function () {
    //function call on load
    readConnectionData();
    // check ip validation on keyup
    checkValidation();
    //function definitions
    $("#ethernetSaveBtn").click(function () {
        // if(checkValidation())
        configureConnectionSettings(this.value);
    });
    $("#enableSshSaveBtn").click(function () {
        // if(checkValidation())
            configureConnectionSettings(this.value);
    });

    $("#reverseSshSaveBtn").click(function () {
        // if(checkValidation())
        if(validateReverseSSHForm()){
            configureConnectionSettings(this.value);
        }
    });

    $("#serialSaveBtn").click(function () {
        if (serialValidate())
            configureConnectionSettings(this.value);
        else
            alert("Please check Serial Details!")

    });
    $("#remoteStorageSaveBtn").click(function () {
        let password = $("#rs-password").val();
        let remoteButton = $("#remoteButton").prop('checked');
        let share = $("#rs-share").val()
        let user = $("#rs-user").val();
        if (remoteButton)
            if (share) {
                if (user) {
                    if (isPasswordsValid && password != "") {
                        configureConnectionSettings(this.value);
                    }
                    else {
                        if (password == '') {
                            $("#rs-password").addClass("is-invalid");
                            $('#rs-password-error').html("Password Can't be Empty!")
                        }
                    }
                }
                else {
                    $("#rs-user-error").addClass("is-invalid");
                    $("#rs-user-error").html("User should not be greater than 16 character")
                }
            }
            else {
                $("#rs-share-error").addClass("is-invalid");
                $("#rs-share-error").html("Share should not be greater than 16 character")
            }
        else {
            configureConnectionSettings(this.value);
        }
    });

    $("#remoteControlEnable").change(function () {
        configureConnectionSettings(this.value);
    });
    $("#password").on("keyup", () => {
        $("#password").removeClass("is-invalid");
        $('#password-email-error').html("")
    })
    $("#saveEmail").click(function () {
        let checkedempty = $("#password").val()
        let smtpServer = $("#smtpServer").val()
        let portNumber = $("#portNumber").val()
        let authenticationCheck = $("#authenticationCheck").prop('checked');
        if (checkLength(smtpServer) && numericValidate(portNumber)) {
            if (authenticationCheck) {
                if (checkedempty != '') {
                    configureEmail();
                    $('#setUpEmailModel').modal('hide');
                }
                else {
                    $("#password").addClass("is-invalid");
                    $('#password-email-error').html("Password Can't be Empty!")
                }
            }
            else {
                configureEmail();
                $('#setUpEmailModel').modal('hide');
            }
        }
        else {

            if (numericValidate(portNumber)) {
                // $("#portNumber").addClass("is-valid");
                $("#portNumber").removeClass("is-invalid");
                $("#port-error").html("");
            }
            else {
                $("#portNumber").addClass("is-invalid");
                // $("#portNumber").removeClass("is-valid");
                $("#port-error").html("Invalid Port Number");
            }
            if (checkLength(smtpServer)) {
                // $("#smtpServer").addClass("is-valid");
                $("#smtpServer").removeClass("is-invalid");
                $("#smtp-error").html("");
            }
            else {
                $("#smtpServer").addClass("is-invalid");
                // $("#smtpServer").removeClass("is-valid");
                $("#smtp-error").html("SMTP Server should be less than 16 character");
            }
        }
    });

    $("#alertMessagesON").change(function () {
        if ($("#alertMessagesON").prop('checked') == false) {
            $("#InfoMessagesON").prop('checked', false);
            $("#warningMessagesON").prop('checked', false);
            $("#alertMessages").prop('checked', false);

            $("#InfoMessagesON").prop('disabled', true);
            $("#warningMessagesON").prop('disabled', true);
            $("#alertMessages").prop('disabled', true);
        } else {
            $("#InfoMessagesON").prop('checked', true);
            $("#warningMessagesON").prop('checked', true);
            $("#alertMessages").prop('checked', true);

            $("#InfoMessagesON").prop('disabled', false);
            $("#warningMessagesON").prop('disabled', false);
            $("#alertMessages").prop('disabled', false);
        }
    });

    $("#authenticationCheck").change(function () {
        if ($("#authenticationCheck").prop('checked') == false) {
            $("#password").val('');
            $("#password").prop('disabled', true);
        } else {
            $("#password").prop('disabled', false);
        }
    });
    $('#myModal').on('hidden.bs.modal', function () {
        if (mymodal.find('.modal-title').text() == "Email Error") {
            $(".modal-header").css({
                "color": "#000",
                "background-color": "#fff"
            });
            $(".close").css({
                "color": "#000"
            });
            var setUpEmailModel = $("#setUpEmailModel");
            setUpEmailModel.modal('show');
        } else if (showMsgBox == true) {
            $(".msg-box").fadeIn();
            setTimeout(function () {
                $(".msg-box").fadeOut();
            }, autoClose);
            showMsgBox = false;
        }
    });
    $("#BAUDRate").keyup(function (e) {
        if (numericValidate(e.target.value)) {
            // $("#BAUDRate").addClass('is-valid');
            $("#BAUDRate").removeClass('is-invalid');
            $("#baudrate-error").html("")
            // return true;
        }
        else {
            // $("#BAUDRate").removeClass('is-valid');
            $("#BAUDRate").addClass('is-invalid');
            $("#baudrate-error").html("Invalid BAUDRate")
            // return false;
        }
    })
    $("#Parity").keyup(function (e) {
        if (numericValidate(e.target.value)) {
            // $("#Parity").addClass('is-valid');  
            $("#Parity").removeClass('is-invalid');
            $("#parity-error").html("")
            // return true;
        }
        else {
            // $("#Parity").removeClass('is-valid');
            $("#Parity").addClass('is-invalid');
            $("#parity-error").html("Invalid Parity");
            // return false;
        }
    })

    $("#DataBits").keyup(function (e) {
        if (numericValidate(e.target.value)) {
            // $("#DataBits").addClass('is-valid');
            $("#DataBits").removeClass('is-invalid');
            $("#databits-error").html("")
            // return true;
        }
        else {
            // $("#DataBits").removeClass('is-valid');
            $("#DataBits").addClass('is-invalid');
            $("#databits-error").html("Invalid DataBits");
            // return false;
        }
    })
    $("#flowControl").keyup(function (e) {
        if (alphaNumericValidate(e.target.value)) {
            // $("#flowControl").addClass('is-valid');
            $("#flowControl").removeClass('is-invalid');
            $("#flowcontrol-error").html("")
            // return true;
        }
        else {
            // $("#flowControl").removeClass('is-valid');
            $("#flowControl").addClass('is-invalid');
            $("#flowcontrol-error").html("Invalid FlowControl")
            // return false;
        }
    })
    function serialValidate() {
        let message = 'You Entered Invalid ';
        let brud = $("#BAUDRate").val()
        let parity = $("#Parity").val()
        let dataBits = $("#DataBits").val()
        let flowControl = $("#flowControl").val()
        if (numericValidate(brud)) {
            // $("#BAUDRate").addClass('is-valid');
            $("#BAUDRate").removeClass('is-invalid');
            $("#baudrate-error").html("")
            // return true;
        }
        else {
            // $("#BAUDRate").removeClass('is-valid');
            $("#BAUDRate").addClass('is-invalid');
            $("#baudrate-error").html("Invalid BAUDRate")
            message += ' BAUDRate ';
            // return false;
        }
        if (numericValidate(parity)) {
            // $("#Parity").addClass('is-valid');  
            $("#Parity").removeClass('is-invalid');
            $("#parity-error").html("")
            // return true;
        }
        else {
            // $("#Parity").removeClass('is-valid');
            $("#Parity").addClass('is-invalid');
            message += ' Parity ';
            $("#parity-error").html("Invalid Parity");
            // return false;
        }
        if (numericValidate(dataBits)) {
            // $("#DataBits").addClass('is-valid');
            $("#DataBits").removeClass('is-invalid');
            $("#databits-error").html("")
            // return true;
        }
        else {
            // $("#DataBits").removeClass('is-valid');
            $("#DataBits").addClass('is-invalid');
            message += ' DataBits ';
            $("#databits-error").html("Invalid DataBits");
            // return false;
        }
        if (alphaNumericValidate(flowControl)) {
            // $("#flowControl").addClass('is-valid');
            $("#flowControl").removeClass('is-invalid');
            $("#flowcontrol-error").html("")
            // return true;
        }
        else {
            // $("#flowControl").removeClass('is-valid');
            $("#flowControl").addClass('is-invalid');
            message += ' FlowControl ';
            $("#flowcontrol-error").html("Ivalid FlowControl")
            // return false;
        }
        if (numericValidate(brud) && numericValidate(parity) && numericValidate(dataBits) && alphaNumericValidate(flowControl)) {
            return true;
        }
        else {
            // alert(message);
            return false;
        }
    }
    // Email Alert validation
    $("#smtpServer").keyup(function (e) {
        if (checkLength(e.target.value)) {
            // $("#smtpServer").addClass("is-valid");
            $("#smtpServer").removeClass("is-invalid");
            $("#smtp-error").html("");
        }
        else {
            $("#smtpServer").addClass("is-invalid");
            // $("#smtpServer").removeClass("is-valid");
            $("#smtp-error").html("SMTP Server should be less than 16 character");
        }
    })
    $("#portNumber").keyup(function (e) {
        if (numericValidate(e.target.value)) {
            // $("#portNumber").addClass("is-valid");
            $("#portNumber").removeClass("is-invalid");
            $("#port-error").html("");
        }
        else {
            $("#portNumber").addClass("is-invalid");
            // $("#portNumber").removeClass("is-valid");
            $("#port-error").html("Invalid Port Number");
        }
    })
    // $("#password").keyup(function(eve){
    //     if(passwordValidation(eve.target.value)) {
    //         if(eve.target.value.length > 16){
    //             isEmailPasswordsValid = false;
    //             $("#password").addClass("is-invalid");
    //             $('#password-email-error').html('Password should not be greater than 16 character');
    //         }
    //         else {
    //             isEmailPasswordsValid = true;
    //             $("#password").removeClass("is-invalid");
    //             $('#password-email-error').html('');
    //         }

    //     } else {
    //         isEmailPasswordsValid = false;
    //         // $("#password").removeClass("is-valid");

    //         $("#password").addClass("is-invalid");
    //         $('#password-email-error').html('Password Must Contain UpperCase,LowerCase,Special Characters and more than 8 Characters');

    //     }
    // })
    // Remote Storage validation
    $("#rs-share").keyup(function (eve) {
        if (eve.target.value.length > 16) {
            isShareValid = false
            $("#rs-share-error").addClass("is-invalid");
            $("#rs-share-error").html("Share should not be greater than 16 character")

        }
        else {
            isShareValid = true
            $("#rs-share-error").removeClass("is-invalid");
            $("#rs-share-error").html("")
        }
    })
    $("#rs-user").keyup(function (eve) {
        if (eve.target.value.length > 16) {
            isUserValid = false
            $("#rs-user-error").addClass("is-invalid");
            $("#rs-user-error").html("User should not be greater than 16 character")

        }
        else {
            isUserValid = true
            $("#rs-user-error").removeClass("is-invalid");
            $("#rs-user-error").html("")
        }
    })
    $("#rs-password").keyup(function (eve) {
        let remoteButton = $("#remoteButton").prop('checked');
        if (remoteButton) {
            if (passwordValidation(eve.target.value)) {
                if (eve.target.value.length > 16) {
                    isPasswordsValid = false;
                    $("#rs-password").addClass("is-invalid");
                    $('#rs-password-error').html('Password should not be greater than 16 character');
                }
                else {
                    isPasswordsValid = true;
                    $("#rs-password").removeClass("is-invalid");
                    $('#rs-password-error').html('');
                }


            } else {
                isPasswordsValid = false;
                // $("#rs-password").removeClass("is-valid");

                $("#rs-password").addClass("is-invalid");
                $('#rs-password-error').html('Password Must Contain UpperCase,LowerCase,Special Characters and more than 8 Characters');

            }

        }
        else {
            $('#rs-password-error').html('');
            $("#rs-password").removeClass("is-invalid");
            // $("#rs-password").addClass("is-valid");   
        }
    })

    $(".togglePassword").click(function () {
        let type = $("#rs-password");
        let typeValue = type.attr("type") === "password" ? "text" : "password";
        // console.log(typeValue);
        if (typeValue == "password") {
            $("#togglePassword").show()
            $("#hidetogglePassword").hide()
        }
        else {
            $("#togglePassword").hide()
            $("#hidetogglePassword").show()
        }
        type.attr("type", typeValue);
        parameters = {
            hidden: typeValue == "password" ? "Yes" : "No",
            requestType: "password_hidden"
        }
        $.ajax({
            type: "get",
            url: "../cgi/cgi_RemoteStorageManager.py",
            contentType: 'application/json',
            dataType: 'json',
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            data: parameters,
            success: function (response) {
            },
            error: function (ex) {
                isCllicked = false;
                $('#test').html(ex.responseText);
            }
        });
    })

})

const saveReverseSSHData = (url,formData) => {
    $('.loaderDiv').css('display', 'block');
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function(response) {
            $('.loaderDiv').css('display', 'none');
			if(response?.status == "error" || response?.status == "fail") {
				$(".modal-header").css({
					"color": "#fff",
					"background-color": "#db4141"
				});
				$(".close").css({
					"color": "#fff"
				});
			}
            mymodal.find('.modal-title').text('Reverse SSH');
            mymodal.find('.modal-body').text(response.description).css({"text-align":"center"});
            
            mymodal.modal('show');

            setTimeout(()=> {
                mymodal.modal("hide")
                $(".modal-header").css({
                    "color": "#000",
                    "background-color": "#fff"
                });
                $(".close").css({
                    "color": "#000"
                });
            },autoClose)
        },

        error: function(err) {
            $('.loaderDiv').css('display', 'none');
            console.log("Failed to send request.");
        }
    });    
}

function validateReverseSSHForm() {
    let enable_reverse =  $("input[name='enReverseSSH']:checked").val();
    if (enable_reverse == "no"){
        return true; // No validation needed if reverse SSH is disabled
    }
    let isValid = true;

    const ip = $("#rs_remote_ip").val().trim();
    const port = $("#rs_remote_port").val().trim();
    const user = $("#rs_remote_user").val().trim();
    const localPort = $("#rs_local_port").val()?.trim();
    const keyFile = $("#rs_key_path")[0].files[0];
    const fileExist = $("#key_file_name").text();

    const ipRegex = /^(?!-)(?:[0-9]{1,3}\.){3}[0-9]{1,3}$|^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; // IPv4 or domain
    const portRegex = /^(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]?\d{1,4})$/;

    // Remote IP
    if (!ip || !ipRegex.test(ip)) {
        $("#rs_remote_ip-error").text("Enter a valid IP address or domain.");
        isValid = false;
    } else {
        $("#rs_remote_ip-error").text("");
    }

    // Remote Port
    if (!port || !portRegex.test(port)) {
        $("#rs_remote_port-error").text("Enter a valid port (1–65535).");
        isValid = false;
    } else {
        $("#rs_remote_port-error").text("");
    }

    // Remote User
    if (!user) {
        $("#rs_remote_user-error").text("Remote user is required.");
        isValid = false;
    } else {
        $("#rs_remote_user-error").text("");
    }

    // Local Port
    // if (!localPort || !portRegex.test(localPort)) {
    //     $("#rs_local_port-error").text("Enter a valid local port (1–65535).");
    //     isValid = false;
    // } else {
    //     $("#rs_local_port-error").text("");
    // }

    // Key File
    if (!keyFile) {
        if (!fileExist) {
            $("#rs_key_path-error").text("Key file is required.");
            isValid = false;
        } else {
            $("#rs_key_path-error").text("");
        }
    } else {
        const allowedExtensions = ['pem', 'key'];
        const fileExt = keyFile.name.split('.').pop().toLowerCase();

        if (typeof enable_reverse !== 'undefined' && enable_reverse === "yes" && !fileExist) {
            if (!allowedExtensions.includes(fileExt)) {
                $("#rs_key_path-error").text("Only .pem or .key files are allowed.");
                isValid = false;
            } else {
                $("#rs_key_path-error").text("");
                $("#key_file_name").text(`Selected file: ${keyFile.name}`);
            }
        } else {
            $("#rs_key_path-error").text("");
        }
    }

    return isValid;
}
$("#rs_remote_ip").on("input", validateReverseSSHForm);
$("#rs_remote_port").on("input", validateReverseSSHForm);
$("#rs_remote_user").on("input", validateReverseSSHForm);
$("#rs_local_port").on("input", validateReverseSSHForm);
$("#rs_key_path").on("change", validateReverseSSHForm);