package cn.forevermc.launcher.view.components.control;

import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import lombok.Getter;
import lombok.Setter;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.CallbackArgReturn;

/**
 * MC 选择器
 *
 * @author 夜雨
 * @since 2022-11-23 17:04
 */
public class MCSelector<T> extends MCButton {

	/** 数据列表 */
	@Getter
	private final ObservableList<T> items;

	/** 字符串转换器 */
	@Setter
	private CallbackArgReturn<T, String> stringConverter;

	private final ObjectProperty<T> value;

	public MCSelector() {
		items = FXCollections.observableArrayList();
		value = new SimpleObjectProperty<>();

		// 监听值
		value.addListener((obs, o, newValue) -> {
			if (stringConverter == null) {
				if (newValue == null) {
					label.setText("");
				} else {
					label.setText(newValue.toString());
				}
			} else {
				label.setText(stringConverter.handler(newValue));
			}
		});

		// 点击切换
		setOnAction(e -> {
			if (TimiJava.isNotEmpty(items)) {
				int i = items.indexOf(value.get()) + 1;
				value.set(items.get(i == items.size() ? 0 : i));
			}
		});
	}

	/**
	 * 选择数据
	 *
	 * @param value 目标数据
	 */
	public void setValue(T value) {
		this.value.set(value);
	}

	/** @return 当前选择 */
	public T getValue() {
		return value.get();
	}

	/** @return 值监听 */
	public ObjectProperty<T> valueProperty() {
		return value;
	}
}
