package aalg.mailer;

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

import aalg.crypto.IAssymetricCipher;
import aalg.crypto.IPrivateKey;
import aalg.crypto.IPublicKey;
import aalg.crypto.IStreamDecryptor;
import aalg.crypto.IStreamEncryptor;

public class Message implements IPersistable {
	
	private final HugeId msgId = new HugeId();
	private IMessageData data;

	private IAssymetricCipher<IPrivateKey, IPublicKey> cipher;
	
	public void write (final OutputStream stream) throws IOException {
		msgId.write(stream);
	
		final IStreamEncryptor encryptor = cipher.getEncryptor();
		encryptor.initialize(stream);
		
		MessageDataFactory.getInstance().write(encryptor.getSourceStream(), data);
	}

	@Override
	public void read(final InputStream stream) throws IOException {
		msgId.read(stream);
		
		final IStreamDecryptor decryptor = cipher.getDecryptor();
		decryptor.initialize(stream);
		
		data = MessageDataFactory.getInstance().read(decryptor.getSourceStream());
	}
	
	public IMessageData getData() {
		return data;
	}

	public void setData(IMessageData data) {
		this.data = data;
	}

	public HugeId getMsgId() {
		return msgId;
	}
}
