package com.github.maximilientyc.conversations.commands;

import com.github.maximilientyc.conversations.domain.Conversation;
import com.github.maximilientyc.conversations.domain.Message;
import com.github.maximilientyc.conversations.domain.repositories.ConversationRepository;
import com.github.maximilientyc.conversations.domain.repositories.MessageRepository;

/**
 * Created by @maximilientyc on 26/03/2016.
 */
public class PostMessageCommand {

	private final Message message;
	private final MessageRepository messageRepository;
	private final ConversationRepository conversationRepository;

	public PostMessageCommand(Message message, MessageRepository messageRepository, ConversationRepository conversationRepository) {
		this.message = message;
		this.messageRepository = messageRepository;
		this.conversationRepository = conversationRepository;
	}

	public void execute() {
		Conversation conversation = conversationRepository.get(message.getConversationId());
		boolean conversationContainsMessageParticipant = conversation.getParticipants().contains(message.getPostedBy());
		if (!conversationContainsMessageParticipant) {
			// TODO: extract into a dedicated validator
			throw new IllegalArgumentException("Cannot post message, reason: not a participant.");
		}
		messageRepository.add(message);

		UpdateConversationLastActiveCommand updateConversationLastActiveCommand = new UpdateConversationLastActiveCommand(conversation, message.getPostedOn(), conversationRepository);
		updateConversationLastActiveCommand.execute();
	}
}

@@ -848,19 +848,33 @@
 sitory;%0A
+%09%09validate();%0A
 %09%7D%0A
-
 %0A%09public
@@ -977,16 +977,498 @@
 onId());
+%0A%0A%09%09messageRepository.add(message);%0A%0A%09%09UpdateConversationLastActiveCommand updateConversationLastActiveCommand = new UpdateConversationLastActiveCommand(conversation, message.getPostedOn(), conversationRepository);%0A%09%09updateConversationLastActiveCommand.execute();%0A%09%7D%0A%0A%09private void validate() %7B%0A%09%09validateConversationContainsPostedBy();%0A%09%7D%0A%0A%09private void validateConversationContainsPostedBy() %7B%0A%09%09Conversation conversation = conversationRepository.get(message.getConversationId());
 %0A%09%09boole
@@ -1628,55 +1628,8 @@
 ) %7B%0A
-%09%09%09// TODO: extract into a dedicated validator%0A
 %09%09%09t
@@ -1718,274 +1718,12 @@
 %22);%0A
+
 %09%09%7D%0A
-%09%09messageRepository.add(message);%0A%0A%09%09UpdateConversationLastActiveCommand updateConversationLastActiveCommand = new UpdateConversationLastActiveCommand(conversation, message.getPostedOn(), conversationRepository);%0A%09%09updateConversationLastActiveCommand.execute();%0A
 %09%7D%0A%7D

refactor post message command validation