poem.boundary.internal.command_handler.PickRandomPoem Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of poem-hexagon-nextgen Show documentation
Show all versions of poem-hexagon-nextgen Show documentation
This is the next generation of the poem-hexagon application.
package poem.boundary.internal.command_handler;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import poem.boundary.driven_port.IObtainPoems;
import poem.boundary.internal.domain.Poem;
import poem.boundary.internal.domain.RandomPoemPicker;
import poem.command.AskForPoem;
import poem.event.RandomVersesPicked;
/**
* The command handler for displaying a random poem.
*
* @author b_muth
*
*/
public class PickRandomPoem implements Function {
private IObtainPoems poemObtainer;
private RandomPoemPicker randomPoemPicker;
public PickRandomPoem(IObtainPoems poemObtainer) {
this.poemObtainer = poemObtainer;
this.randomPoemPicker = new RandomPoemPicker();
}
@Override
public Object[] apply(AskForPoem askForPoem) {
List poems = obtainPoems(askForPoem);
Optional poem = pickRandomPoem(poems);
Object[] singleElementArray = getSinglePoemVerses(poem);
return singleElementArray;
}
private List obtainPoems(AskForPoem askForPoem) {
String language = askForPoem.getLanguage();
String[] poems = poemObtainer.getMePoems(language);
List poemDomainObjects = Arrays.stream(poems).map(Poem::new).collect(Collectors.toList());
return poemDomainObjects;
}
private Optional pickRandomPoem(List poemList) {
Optional randomPoem = randomPoemPicker.pickPoem(poemList);
return randomPoem;
}
private Object[] getSinglePoemVerses(Optional poem) {
return poem.map(p -> new Object[] { new RandomVersesPicked(p.getVerses()) }).orElse(new Object[0]);
}
}