$(function () {
    var errorDiv = $('<div>').addClass('error-message');

    function error(msg) {
        $('h1').after(errorDiv.text(msg));
    }

    $('#has-password').change(function () {
        $('#password, #save-online').prop('disabled', !this.checked);
    });

    $('#create-csr').click(function () {
        var name = $('#name').val();

        if (name.length === 0) {
            error("Name can't be empty");
            return;
        }

        if (!/^[A-Za-z0-9\-]+$/.test(name)) {
            error("Only alphanumeric and - allowed in name");
            return;
        }

        var user = $('#user-input').val();

        var keys = forge.pki.rsa.generateKeyPair(1024);
        var csr = forge.pki.createCertificationRequest();
        var commonName  = name + '.' + user;

        csr.publicKey = keys.publicKey;
        csr.setSubject([{
            name: 'commonName',
            value: commonName
        }]);
        csr.sign(keys.privateKey);
        var csrPem = forge.pki.certificationRequestToPem(csr);

        var newCertParams = {
            csr: csrPem,
            name: name
        };

        var keyPem = "";

        if ($('#has-password').prop('checked')) {
            keyPem = forge.pki.encryptRsaPrivateKey(keys.privateKey, $('#password').val());
            if ($('#save-online').prop('checked')) {
                newCertParams.key = keyPem;
            }
        } else {
            keyPem = forge.pki.privateKeyToPem(keys.privateKey);
        }

        $.post('/panel/certificates/new', newCertParams, function (data) {
            if (data.success) {
                var zip = new JSZip();
                zip.file(commonName + '.key', keyPem);

                for(var file in data.zip) {
                    if (!data.zip.hasOwnProperty(file)) continue;
                    zip.file(file, data.zip[file]);
                }

                var content = zip.generate({type:"blob"});
                saveAs(content, commonName + '-vpn.zip');
                location.href = '/panel';
            } else {
                error(data.error);
            }
        }, 'json');
    });
});
