package de.siphalor.was.visual.jfx.controller;

import de.siphalor.was.WhatAStorage;
import de.siphalor.was.content.lang.I18n;
import de.siphalor.was.game.Options;
import javafx.fxml.FXML;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ToggleButton;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;

public class OptionsController {
	private Runnable exitRunnable;

	public ChoiceBox<LangEntry> languageChoice;
	public ToggleButton allowQuestResolvingToggle;
	public ToggleButton autoQuestRefillToggle;

	public void beforeOpen(@NotNull Runnable exitRunnable) {
		Options options = WhatAStorage.getInstance().getOptions();
		this.exitRunnable = exitRunnable;

		I18n i18n = I18n.getInstance();
		String curLang = i18n.getLang().getCode();

		languageChoice.getItems().clear();
		String[] langs = WhatAStorage.getInstance().getLangs();
		Arrays.sort(langs);
		for (String lang : langs) {
			LangEntry langEntry = new LangEntry(lang, i18n.getString("langs." + lang));
			languageChoice.getItems().add(langEntry);
			if (curLang.equals(lang)) {
				languageChoice.setValue(langEntry);
			}
		}

		allowQuestResolvingToggle.setSelected(options.getAllowQuestResolving());
		autoQuestRefillToggle.setSelected(options.getAutoRefillQuests());
	}

	@FXML
	private void onLeaveClicked() {
		Options options = WhatAStorage.getInstance().getOptions();

		String oldLang = I18n.getInstance().getLang().getCode();
		I18n.getInstance().setLang(languageChoice.getValue().getCode(), WhatAStorage.getInstance().getContentManager());
		options.setAllowQuestResolving(allowQuestResolvingToggle.isSelected());
		options.setAutoRefillQuests(autoQuestRefillToggle.isSelected());

		options.save();

		if (!oldLang.equals(I18n.getInstance().getLang().getCode())) {
			WhatAStorage.getInstance().invalidateI18n();
		}

		exitRunnable.run();
	}

	private static class LangEntry {
		private final String code;
		private final String name;

		private LangEntry(String code, String name) {
			this.code = code;
			this.name = name;
		}

		@Override
		public String toString() {
			return name;
		}

		public String getCode() {
			return code;
		}
	}
}
