package xyz.thastertyn.UserInterface.Dialogs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.googlecode.lanterna.gui2.Button;
import com.googlecode.lanterna.gui2.ComboBox;
import com.googlecode.lanterna.gui2.EmptySpace;
import com.googlecode.lanterna.gui2.GridLayout;
import com.googlecode.lanterna.gui2.LocalizedString;
import com.googlecode.lanterna.gui2.Panel;
import com.googlecode.lanterna.gui2.Window;
import com.googlecode.lanterna.gui2.WindowBasedTextGUI;
import com.googlecode.lanterna.gui2.dialogs.DialogWindow;

import xyz.thastertyn.Types.Choice;
import xyz.thastertyn.Types.Option;
import xyz.thastertyn.Types.Options;

public class OptionsDialog extends DialogWindow {

	private List<ComboBox<Option>> boxs;

	private boolean useData = false;
	
	public OptionsDialog(Options[] options)
	{
		super("Vyber si");

		boxs = new ArrayList<>();

		for(int i = 0; i < options.length; i++)
		{
			boxs.add(new ComboBox<Option>(options[i].getOptions()));

			// Add the title of option to the dialogs title
			if(options.length == 1 || i == 0)
			{
				setTitle(getTitle() + " \"" + options[i].getTitle() + "\"");
			}else{
				setTitle(getTitle() + " a \"" + options[i].getTitle() + "\"");
			}
		}

		for(int i = 0; i < options.length; i++)
		{
			for(int j = 0; j < options[i].getOptions().size(); j++)
			{
				if(options[i].getOptions().get(j).isDefault())
				{
					boxs.get(i).setSelectedIndex(j);
				}
			}
		}

		Panel mainPanel = new Panel(new GridLayout(1)
				.setLeftMarginSize(1)
				.setRightMarginSize(1));

		Panel optionPanel = new Panel(new GridLayout(3))
		.addTo(mainPanel);



		for(int i = 0; i < options.length; i++)
		{
			optionPanel.addComponent(boxs.get(i));

			if(i != options.length - 1)
			{
				optionPanel.addComponent(new EmptySpace());
			}
		}

		new Panel(new GridLayout(2).setHorizontalSpacing(1))
			.addComponent(
				new Button(LocalizedString.OK.toString(), this::onOK)
					.setLayoutData(GridLayout.createLayoutData(
						GridLayout.Alignment.CENTER,
						GridLayout.Alignment.CENTER,
						true,
						false)))
			.addComponent(
				new Button(LocalizedString.Cancel.toString(), this::onCancel))
				.addTo(mainPanel);


		setHints(Arrays.asList(Window.Hint.CENTERED));
		setComponent(mainPanel);
	}

	public void onOK()
	{
		close();
		useData = true;
	}

	public void onCancel()
	{
		close();
	}

	@Override
	public Optional<Choice> showDialog(WindowBasedTextGUI textGUI) {
		super.showDialog(textGUI);

		Choice c = new Choice(
			boxs.stream()
				.map(box -> box.getSelectedItem().getValue())
				.collect(Collectors.toList()));

		return (useData) ?
			// User pressed Ok
			Optional.of(c)
			:
			// User pressed Cancel
			Optional.empty();
	}
}
