package cli.link;

import cli.Subcommand;

import java.util.Arrays;
import java.util.stream.Collectors;

public class LinkCommands extends Subcommand {

	private final LinkCliAdapter linkCliAdapter;

	public LinkCommands(LinkCliAdapter linkCliAdapter) {
		this.linkCliAdapter = linkCliAdapter;
		commands.put("add", this::addLink);
		commands.put("get", this::getAll);
		commands.put("category", this::getByCategory);
		commands.put("user", this::getByUser);
		commands.put("tag", this::getByTag);
		commands.put("hosts", this::groupByHosts);
	}

	@Override
	public String getSubcommand() {
		return "link";
	}

	@Override
	public String getUsage() {
		return "Usage: " + System.lineSeparator() +
				getSubcommand() + " add http://example.org yourUsername [category1 category2 .. categoryN]" + System.lineSeparator() +
				getSubcommand() + " get " + System.lineSeparator() +
				getSubcommand() + " category aCategoryName " + System.lineSeparator() +
				getSubcommand() + " tag aTagName " + System.lineSeparator() +
				getSubcommand() + " user aUserName " + System.lineSeparator() +
				getSubcommand() + " hosts";

	}

	private String addLink(String[] args) {
		linkCliAdapter.addLink(args[1],
		                       Arrays.stream(Arrays.copyOfRange(args, 3, args.length)).collect(Collectors.toSet()),
		                       args[2]);
		return "Added the new Link";
	}

	private String getAll(String[] args) {
		var firstLine = "All available Links:" + System.lineSeparator();
		return firstLine + String.join(System.lineSeparator(), linkCliAdapter.getLinks());
	}

	private String getByCategory(String[] args) {
		var firstLine = "All available Links for the category:" + System.lineSeparator();
		return firstLine + String.join(System.lineSeparator(), linkCliAdapter.getLinksForCategory(args[1]));
	}

	private String getByUser(String[] args) {
		var firstLine = "All available Links for the user:" + System.lineSeparator();
		return firstLine + String.join(System.lineSeparator(), linkCliAdapter.getLinksForUser(args[1]));
	}

	private String getByTag(String[] args) {
		var firstLine = "All available Links for the tag:" + System.lineSeparator();
		return firstLine + String.join(System.lineSeparator(), linkCliAdapter.getLinksForTag(args[1]));
	}

	private String groupByHosts(String[] strings) {
		var firstLine = "All available Links grouped by the host names:" + System.lineSeparator();
		return firstLine + String.join(System.lineSeparator(), linkCliAdapter.groupByHosts());
	}
}
