/*
 * Read the message, and proper actions.
 * =====================================
 *
 * If a message is being read, depending on its status(encryption and
 * signature), decryption may be done, and signature will be verified.
 *   In such case, passphrase for decryption with PKI will be read from the
 * argument `passphrase`, while passphrase for only-passphrase encrypted
 * message will be read from `argv.passphrase`.
 *
 * If a message is a certificate, or a signature to identity, or an identity,
 * or a revocation-magic, it will be applied to the database.
 */
function determine(str){
    var result = false, type;
    for(var i in $.pack.types){
        type = $.pack.types[i];
        try{
            result = $.pack(type).unpack(str);
            if(Boolean(result)) break;
        } catch(e){
            console.error(type, ':', e);
            return false;
        };
    };
    if(result)
        return {type: type, result: result};
    return false;
};

var correspondents = {
    message: require('./read.encsig.js'),
};

module.exports = function(operand, ioAgent){
    ioAgent.input('message')(function(err, textBuf){
        if(err) return ioAgent.error($.error('stop'));

        try{
            var determined = determine(textBuf);
        } catch(e){
            return ioAgent.error($.error('unable-to-recognize-message'));
        };

        if(correspondents[determined.type]){
            ioAgent.info('message-type', determined.type);
            correspondents[determined.type](determined.result, ioAgent);
        } else
            ioAgent.error($.error('unable-to-recognize-message'));
    });
};
