package poem.hexagon.internal.commandhandler;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import poem.hexagon.boundary.AskForPoem;
import poem.hexagon.boundary.drivenport.IObtainPoems;
import poem.hexagon.boundary.drivenport.IWriteLines;
import poem.hexagon.internal.domain.Poem;
import poem.hexagon.internal.domain.RandomPoemPicker;

/**
 * The command handler for displaying a random poem.
 * 
 * Inspired by a talk by A. Cockburn and T. Pierrain on hexagonal
 * architecture: https://www.youtube.com/watch?v=th4AgBcrEHA
 * 
 * @author b_muth
 *
 */
public class DisplayRandomPoem implements Consumer<AskForPoem> {
	private IObtainPoems poemObtainer;
	private RandomPoemPicker randomPoemPicker;
	private IWriteLines lineWriter;

	public DisplayRandomPoem(IObtainPoems poemObtainer, IWriteLines lineWriter) {
		this.poemObtainer = poemObtainer;
		this.randomPoemPicker = new RandomPoemPicker();
		this.lineWriter = lineWriter;
	}

	@Override
	public void accept(AskForPoem askForPoem) {
		String[] poems = obtainPoems(askForPoem);
		List<Poem> poemList = createDomainObjects(poems);
		String poem = pickRandomPoemFromList(poemList);
		displayPoem(poem);		
	}

	private String[] obtainPoems(AskForPoem askForPoem) {
		String language = askForPoem.getLanguage();
		String[] poems = poemObtainer.getMePoems(language);
		return poems;
	}
	
	private List<Poem> createDomainObjects(String[] poems) {
		List<Poem> poemList = Arrays.stream(poems)
			.map(Poem::new)
			.collect(Collectors.toList());
		return poemList;
	}
	
	private String pickRandomPoemFromList(List<Poem> poemList) {
		return randomPoemPicker.pickPoem(poemList);
	}
	
	private void displayPoem(String poem) {
		lineWriter.writeLines(poem);
	}
}

@@ -1061,24 +1061,26 @@
 em) %7B%0A%09%09
-String%5B%5D
+List%3CPoem%3E
  poems =
@@ -1109,60 +1109,8 @@
 m);%0A
-%09%09List%3CPoem%3E poemList = createDomainObjects(poems);%0A
 %09%09St
@@ -1144,28 +1144,25 @@
 romList(poem
-List
+s
 );%0A%09%09display
@@ -1188,24 +1188,26 @@
 private 
-String%5B%5D
+List%3CPoem%3E
  obtainP
@@ -1342,36 +1342,8 @@
 ;%0A%09%09
-return poems;%0A%09%7D%0A%09%0A%09private 
 List
@@ -1353,14 +1353,12 @@
 em%3E 
-create
+poem
 Doma
@@ -1370,51 +1370,15 @@
 ects
-(String%5B%5D poems) %7B%0A%09%09List%3CPoem%3E poemList = 
+ = %0A%09%09%09
 Arra
@@ -1397,16 +1397,17 @@
 ems)%0A%09%09%09
+%09
 .map(Poe
@@ -1414,16 +1414,17 @@
 m::new)%0A
+%09
 %09%09%09.coll
@@ -1462,20 +1462,29 @@
 urn poem
-List
+DomainObjects
 ;%0A%09%7D%0A%09%0A%09

Update DisplayRandomPoem.java