All Downloads are FREE. Search and download functionalities are using the official Maven repository.

poem.boundary.internal.command_handler.PickRandomPoem Maven / Gradle / Ivy

There is a newer version: 0.6.6
Show newest version
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]);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy