package cn.forevermc.launcher.ctrl.pane;

import cn.forevermc.launcher.bean.Config;
import cn.forevermc.launcher.bean.Page;
import cn.forevermc.launcher.ctrl.Main;
import cn.forevermc.launcher.service.PageService;
import cn.forevermc.launcher.view.pages.LangSelectPane;
import lombok.extern.slf4j.Slf4j;
import com.imyeyu.fx.TimiFX;
import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.inject.TimiInject;
import com.imyeyu.inject.annotation.Controller;
import com.imyeyu.inject.annotation.Inject;
import com.imyeyu.inject.annotation.SuperInject;
import com.imyeyu.io.IO;
import com.imyeyu.java.bean.Language;
import com.imyeyu.utils.OS;

/**
 * 语言选择
 *
 * @author 夜雨
 * @since 2022-12-02 00:18
 */
@Slf4j
@Controller
@SuperInject
public class LangSelect extends LangSelectPane implements OS.FileSystem {

	@Inject
	private Config config;

	@Inject
	private Main main;

	@Inject
	private Dialog dialog;

	@Inject
	private PageService pageService;

	public LangSelect() {
		// 确认
		confirm.setOnAction(e -> {
			Language selectedLang = list.getSelectionModel().getSelectedItem();
			if (selectedLang.equals(config.getMain().getLanguage().get())) {
				// 没有修改
				pageService.to(Page.MENU);
				return;
			}
			dialog.setContent(TimiFXUI.MULTILINGUAL.text("tips.restart"));
			dialog.setConfirmEvent(() -> {
				config.getMain().getLanguage().set(selectedLang);
				// JRE
				String jre = System.getProperty("java.home") + SEP + "bin" + SEP + "java";
				// 启动参数
				String param = " -XX:+UnlockExperimentalVMOptions -XX:+UseZGC -jar ";
				// 启动 Jar
				String jar = IO.getJarAbsolutePath(getClass());
				// 重启
				try {
					TimiFX.doRestart(main, jre + param + jar);
				} catch (Exception ex) {
					dialog.setContent(TimiFXUI.MULTILINGUAL.text("tips.restart.error"));
					dialog.setConfirmEvent(null);
					dialog.setCancelEvent(null);
					dialog.setCloseEvent(() -> pageService.to(Page.MENU));
					log.error("restart error", ex);
				}
			});
			dialog.setCancelEvent(() -> pageService.to(Page.MENU));
			dialog.eject();
		});

		// 取消
		cancel.setOnAction(e -> pageService.to(Page.MENU));
	}

	@Override
	public void onShow() {
		list.getItems().setAll(Language.values());
		list.getSelectionModel().select(config.getMain().getLanguage().get());
	}
}
