package com.tipi.conversations.domain.model.conversations;

import java.util.UUID;

/**
 * Created by Maximilien on 03/01/2016.
 */
public class ConversationService {

	private ConversationRepository conversationRepository;

	public ConversationService(ConversationRepository conversationRepository) {
		this.conversationRepository = conversationRepository;
	}

	public void add(Conversation conversation) {
		validateConversation(conversation, "Cannot add conversation, reason: not enough participants.");
		if (conversationRepository.exists(conversation.getConversationId())) {
			throw new IllegalArgumentException("Cannot add conversation, reason: conversation already exists.");
		}
		conversationRepository.save(conversation);
	}

	public void update(Conversation conversation) {
		validateConversation(conversation, "Cannot update conversation, reason: not enough participants.");
		if (!conversationRepository.exists(conversation.getConversationId())) {
			throw new IllegalArgumentException("Cannot update conversation, reason: conversation does not exists.");
		}
		conversationRepository.save(conversation);
	}

	private void validateConversation(Conversation conversation, String s) {
		if (conversation.getParticipants().size() < 2) {
			throw new IllegalArgumentException(s);
		}
	}

	public Conversation getByConversationId(String conversationId) {
		return conversationRepository.findOne(conversationId);
	}

	public String getNextConversationId() {
		return UUID.randomUUID().toString();
	}


	public String getNextMessageId() {
		return UUID.randomUUID().toString();
	}

}

@@ -440,71 +440,173 @@
 tion
-, %22Cannot add conversation, reason: not enough participants.%22);
+);%0A%09%09validateCreateConversation(conversation);%0A%09%09conversationRepository.save(conversation);%0A%09%7D%0A%0A%09private void validateCreateConversation(Conversation conversation) %7B
 %0A%09%09i
@@ -787,53 +787,8 @@
 %09%09%7D%0A
-%09%09conversationRepository.save(conversation);%0A
 %09%7D%0A%0A
@@ -875,74 +875,173 @@
 tion
-, %22Cannot update conversation, reason: not enough participants.%22);
+);%0A%09%09validateUpdateConversation(conversation);%0A%09%09conversationRepository.save(conversation);%0A%09%7D%0A%0A%09private void validateUpdateConversation(Conversation conversation) %7B
 %0A%09%09i
@@ -1227,53 +1227,8 @@
 %09%09%7D%0A
-%09%09conversationRepository.save(conversation);%0A
 %09%7D%0A%0A
@@ -1291,18 +1291,8 @@
 tion
-, String s
 ) %7B%0A
@@ -1380,17 +1380,75 @@
 ception(
-s
+%22Cannot add conversation, reason: not enough participants.%22
 );%0A%09%09%7D%0A%09

Refactor conversation create/update validation