$(function(){
    IDENTITY.on('refresh', composer.refreshSignerList);

    $('#composer-process').click(composer.process);
    $('#composer-add-to')
        .autocomplete({
            minLength: 2,
            source: composer.autoCompleteTo,
        })
        .autocomplete("widget")
            .addClass('dropdown-menu')
    ;
    $('#composer-add-to-btn').click(composer.addReceiver);

    $('#tab-composer').on('click change select', composer.validate);
    $('#composer-protect-method a').on('shown.bs.tab', composer.validate);
    composer.validate();
});

//////////////////////////////////////////////////////////////////////////////

var composer = {};

composer.refreshSignerList = function(data){
    if(!data) data = IDENTITY.list();
    var byList = $('#tab-composer select#composer-signer-list').empty();
    byList.append(
        $('<option>', {"value": ""})
            .text('---- 不进行签署 -----')
    );
    for(var i in data){
        if(!data[i]["HAS-PRIVATE"]) continue;
        byList.append(
            $('<option>', {"value": i})
                .text(
                    '['
                    + i.slice(0, 8).toUpperCase()
                    + '] '
                    + data[i]["LABEL"]
                )
        );
    };
};

composer.validate = function(){
    var signerChoosen = Boolean($('#composer-signer-list').val());

    var receiverSet = Boolean($('#composer-to span').length),
        encryptPassGiven = Boolean($('#composer-encrypt-passphrase').val()),
        messageWritten = Boolean($('#composer-message').val());

    var method =
        $('#composer-protect-method .active[name="method"]')
            .attr('data-value');


    $('#composer-process').attr(
        "disabled",
        Boolean(
            !messageWritten ||
            ('no' == method && !signerChoosen) ||
            ('pki' == method && !receiverSet ) ||
            ('passphrase' == method && !encryptPassGiven)
        )
    );
    $('#composer-signer-passphrase').attr("disabled", !signerChoosen);
    $('#composer-signer-algorithm').attr("disabled", !signerChoosen);

};

composer.autoCompleteTo = function(request, callback){
    var data = IDENTITY.list();
    var term = request.term.toLowerCase();
    var searchID = /^[0-9a-f]{4,64}$/.test(term);

    var matched = [];

    for(var id in data){
        if(
            (searchID && id.substr(0, term.length) == term) ||
            (data[id]["LABEL"].toLowerCase().indexOf(term) >= 0)
        ){
            if($('span[name="send-to-' + id + '"]').length > 0) continue;
            matched.push({label: data[id]["LABEL"], value: id});
        };
    };
    callback(matched);
};

composer.addReceiver = function(){
    var id = $('#composer-add-to').val().trim().toLowerCase();
    var identity = IDENTITY.list(id);

    if(!identity) return;

    if($('span[name="send-to-' + id + '"]').length <= 0){
        var newMark = 
            $('<span>', {
                name: 'send-to-' + id,
            })
                .addClass('label label-warning')
                .css("margin-right", "2px")
                .data('id', id)
        ;

        newMark
            .text(identity["LABEL"])
            .append(
                $('<button>')
                    .addClass('btn btn-xs btn-link')
                    .text('删')
                    .click(function(){
                        $('span[name="send-to-' + id + '"]').remove();
                        if($('#composer-to span').length < 1)
                            $('#composer-to').text('无');
                    })
            )
        ;

        if($('#composer-to span').length < 1) $('#composer-to').empty();
        
        $('#composer-to').append(newMark);
    };

    $('#composer-add-to').val('');
};

/****************************************************************************/

composer.process = function(){
    var method =
        $('#composer-protect-method .active[name="method"]')
            .attr('data-value');
    var message = $('#composer-message').val(),
        encryptPassphrase = $('#composer-encrypt-passphrase').val();
    var pkiReceivers = [];

    var signer = $('#composer-signer-list').val(),
        signAlgo = $('#composer-signer-algorithm').val(), 
        signerPassphrase = $('#composer-signer-passphrase').val();

    var operand = '';
    
    $('#composer-to span').each(function(){
        pkiReceivers.push($(this).data('id'));
    });

    var passphrase = null,
        data = {
            plaintext: message,
        },
        argv = {
            plaintext: {
                encoding: 'utf-8',
            },
        }
    ;

    if(signer){
        data["signer-identity"] = signer;
        data["sign-hash-algorithm"] = signAlgo;
        passphrase = signerPassphrase;
    };

    switch(method){
        case 'passphrase':
            operand = (Boolean(signer)?'encsig':'encrypt');
            data["encrypt-passphrase"] = encryptPassphrase;
            data["encrypt-with-only-passphrase"] = true;
            break;
        case 'pki':
            operand = (Boolean(signer)?'encsig':'encrypt');
            data["encrypt-with-only-passphrase"] = false;
            data["receiver-identities"] = pkiReceivers;
            break;
        case 'no':
            operand = 'sign';
            break;
        default:
            alert('Not Implemented');
            break;
    };

    var desc = (new Date().toString());

    var session = COMMAND(operand, data, argv);

    session.done(composer.showResult);
};

/****************************************************************************/
composer.showResult = function(ciphertext){
    var desc = '报文结果';
    var newBox = 
        COMMON.insertResultBox('tab-composer-result-area', 'success', desc);

    newBox.body 
        .append(
            $('<span>')
                .text('您的密文已经产生如下，请用浏览器，右键菜单，全选，复制。')
        )
    ;

    var textarea = 
        $('<textarea>', {rows: 10})
            .appendTo(newBox.body)
            .addClass('form-control')
            .attr("readonly", "readonly")
            .val(ciphertext)
    ;

    $.notify('新的报文已经生成。', 'success');
};
