$(function () {
    var keyLocation = $('#key-location');
    var keyLocationContainer = keyLocation.parent();
    var decryptKeyCheckbox = $('#decrypt-key');
    var decryptKeyCheckboxContainer = decryptKeyCheckbox.parent();
    var password = $('#password');
    var passwordContainer = password.parent();
    var embedConfiguration = $('#want-embedded');
    var embedConfigurationContainer = embedConfiguration.parent();

    decryptKeyCheckbox.change(function() {
        if (this.checked) {
            passwordContainer.show();
            return;
        }

        passwordContainer.hide();
    });

    function handleKeyFile(element) {
        var keyFileContent = element.target.result;

        console.log(keyFileContent);
        // TODO: Add keyfile to embedded server config using forge
    }

    keyLocationContainer.on('show', function() {
        decryptKeyCheckboxContainer.show();
    });

    keyLocationContainer.on('hide', function() {
        decryptKeyCheckboxContainer.hide();
    });

    decryptKeyCheckboxContainer.on('show', function() {
        if (decryptKeyCheckbox.prop('checked') === true) {
            passwordContainer.show();
        }
    });

    decryptKeyCheckboxContainer.on('hide', function() {
        passwordContainer.hide();
        passwordContainer.val('');
    });

    function setFileSelectVisibility() {
        var selectedOption = $('#certificate option:selected');

        if (selectedOption.data('hasPrivateKey') == '1') {
            keyLocationContainer.show();
            return;
        }

        keyLocationContainer.hide();
    }

    keyLocation.change(function () {
        var file = this.files[0];
        var reader = new FileReader();

        reader.onload = handleKeyFile;

        reader.readAsText(file);
    });

    embedConfiguration.change(function () {
        if (this.checked) {
            setFileSelectVisibility();
            decryptKeyCheckboxContainer.show();
            return;
        }

        decryptKeyCheckboxContainer.hide();
        keyLocationContainer.hide();
    });
});