$(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();
    var keyFileContent = null;
    var buildConfigZip = $('#build-config-zip');
    var getCertificateForm = $('#get-certificate-form');

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

        passwordContainer.hide();
    });

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

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

    // Retrieve zip file with post
    getCertificateForm.submit(function (event) {
        event.preventDefault();
    });

    function handleZipResult(data) {
        //var blob = new Blob(data, {type: 'application/zip'});
        var blobUrl = URL.createObjectURL(data);
        saveBlobUrl(blobUrl, 'config.zip');
    }

    function handleEmbeddedResult(data) {
        console.log("I haven't implemented this yet")
    }

    var downloadElement = document.createElement("a");
    document.body.appendChild(downloadElement);
    downloadElement.style = "display: none";

    function saveBlobUrl(url, fileName) {
        downloadElement.href = url;
        downloadElement.download = fileName;
        downloadElement.click();
        window.URL.revokeObjectURL(url);
    }

    function submitCertificateForm(event) {
        console.log('submitCert');
        var url = getCertificateForm.attr('action'),
            method = getCertificateForm.attr('method'),
            data = getCertificateForm.serialize(),
            dataType = 'application/zip',
            handler = handleZipResult;

        if (embedConfiguration.checked) {
            dataType = 'text/plain';
            handler = handleEmbeddedResult;
        }

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                //this.response is what you're looking for
                handler(this.response);
            }
        };
        xhr.open(method, url);
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.responseType = 'blob';
        xhr.send(data);
    }

    buildConfigZip.on('click', submitCertificateForm);

    // Load content of embedded server config
    // Put keyfile content in embedded server config if it is not null
    // If the decrypt key checkbox is checked, attempt to decrypt the private key in the embedded server config
    // Offer the decrypted server config up as a file

    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();
    });
});