package cn.forevermc.launcher.view.components;

import cn.forevermc.launcher.bean.Game;
import cn.forevermc.launcher.util.Resources;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import com.imyeyu.fx.icon.TimiFXIcon;
import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.fx.utils.BorderStroke;

import javax.swing.border.StrokeBorder;

/**
 * 登录方式选择器
 *
 * @author 夜雨
 * @since 2024-08-03 11:41
 */
public class LoginTypeSelector extends StackPane {

	private final ObservableList<Game.Option.LoginType> items;

	private final ObjectProperty<Game.Option.LoginType> value;

	private final BooleanProperty requiredOffline;

	public LoginTypeSelector() {
		items = FXCollections.observableArrayList();
		items.setAll(Game.Option.LoginType.OFFLINE, Game.Option.LoginType.FOREVER_MC); // 暂不支持 MOJANG
		value = new SimpleObjectProperty<>();
		requiredOffline = new SimpleBooleanProperty(false);

		Text offline = TimiFXIcon.fromName("UNLINK", TimiFXUI.Colorful.WHITE);
		ImageView foreverMC = new ImageView(Resources.F);
		ImageView mojang = new ImageView(Resources.M);

		setMaxSize(16, 16);

		// ---------- 事件 ----------

		addEventFilter(MouseEvent.MOUSE_CLICKED, e -> {
			if (!isRequiredOffline()) {
				int nextIndex = items.indexOf(value.get()) + 1;
				if (items.size() <= nextIndex) {
					nextIndex = 0;
				}
				value.set(items.get(nextIndex));
			}
		});

		value.addListener((obs, o, n) -> getChildren().setAll(switch (value.get()) {
			case OFFLINE -> offline;
			case FOREVER_MC -> foreverMC;
			case MOJANG -> mojang;
		}));

		requiredOffline.addListener((obs, o, n) -> {
			if (isRequiredOffline()) {
				value.set(Game.Option.LoginType.OFFLINE);
			}
		});
	}

	public boolean isOffline() {
		return value.get() == Game.Option.LoginType.OFFLINE;
	}

	public boolean isOnline() {
		return !isOffline();
	}

	public boolean isForeverMC() {
		return value.get() == Game.Option.LoginType.FOREVER_MC;
	}

	public boolean isMojang() {
		return value.get() == Game.Option.LoginType.MOJANG;
	}

	public void setValue(Game.Option.LoginType value) {
		this.value.set(value);
	}

	public Game.Option.LoginType getValue() {
		return value.get();
	}

	public ObjectProperty<Game.Option.LoginType> valueProperty() {
		return value;
	}

	public void setRequiredOffline(boolean requiredOffline) {
		this.requiredOffline.set(requiredOffline);
	}

	public boolean isRequiredOffline() {
		return requiredOffline.get();
	}

	public BooleanProperty requiredOfflineProperty() {
		return requiredOffline;
	}
}