package aalg.mailer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import aalg.crypto.IAssymetricKeyIo;
import aalg.crypto.IPrivateKey;
import aalg.crypto.IPublicKey;

public class CommandStorMsg<PRIV extends IPrivateKey, PUB extends IPublicKey> implements ICommand {
	
	private final IAssymetricKeyIo<PRIV, PUB> keyIo;
	private PUB kPubTmp;
	private final Message message;
	
	public CommandStorMsg(final IAssymetricKeyIo<PRIV, PUB> keyIo) {
		this.keyIo = keyIo;
		this.message = new Message();
	}
	
	@Override
	public void write(final OutputStream stream) throws IOException {
		keyIo.writePublicKey(kPubTmp, stream);
		message.write(stream);
	}

	@Override
	public void read(final InputStream stream) throws IOException {
		kPubTmp = keyIo.readPublicKey(stream);
		message.read(stream);
	}

	@Override
	public void execute(final CommandContext context) {
		context.getDatabase().storeMessage(message);
	}

}
