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

import cn.forevermc.launcher.util.Resources;
import cn.forevermc.launcher.util.Sound;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Border;
import javafx.scene.layout.StackPane;
import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.fx.utils.BgImage;
import com.imyeyu.fx.utils.BorderStroke;

/**
 * MC 复选框
 *
 * @author 夜雨
 * @since 2022-11-24 01:14
 */
public class MCCheckBox extends StackPane implements TimiFXUI {

	private static final Border BORDER_WHITE = new BorderStroke(Colorful.WHITE).width(2).build();
	private static final Border BORDER_BLACK = new BorderStroke(Colorful.BLACK).width(2).build();

	private final BooleanProperty selected;
	private final ObjectProperty<Label> label;

	public MCCheckBox() {
		selected = new SimpleBooleanProperty(false);
		label = new SimpleObjectProperty<>();

		ImageView check = new ImageView(Resources.CHECK);
		check.visibleProperty().bind(selected);

		setMaxSize(34, 34);
		setPrefSize(34, 34);
		borderProperty().bind(Bindings.when(hoverProperty()).then(BORDER_WHITE).otherwise(BORDER_BLACK));
		getChildren().addAll(new StackPane() {{
			setBackground(new BgImage(Resources.BTN).build());
			getChildren().add(new StackPane() {{
				setOpacity(.6);
				setBackground(BG.BLACK);
			}});
		}}, check);

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

		EventHandler<MouseEvent> clickEvent = e -> {
			selected.set(!selected.get());
			Sound.CLICK.play();
		};
		addEventFilter(MouseEvent.MOUSE_PRESSED, clickEvent);
		label.addListener((obs, oldLabel, newLabel) -> {
			if (newLabel != null) {
				newLabel.addEventFilter(MouseEvent.MOUSE_PRESSED, clickEvent);
			}
			if (oldLabel != null) {
				oldLabel.removeEventFilter(MouseEvent.MOUSE_PRESSED, clickEvent);
			}
		});
	}

	/** @return true 为已选中 */
	public boolean isSelected() {
		return selected.get();
	}

	/** @param selected true 为已选中 */
	public void setSelected(boolean selected) {
		this.selected.set(selected);
	}

	/** @return 选中监听 */
	public BooleanProperty selectedProperty() {
		return selected;
	}

	/** @return 标签，此标签点击触发复选 */
	public Label getLabel() {
		return label.get();
	}

	/** @param label 设置标签，此标签点击触发复选 */
	public void setLabel(Label label) {
		this.label.set(label);
	}

	/** @return 标签监听，此标签点击触发复选 */
	public ObjectProperty<Label> labelProperty() {
		return label;
	}
}
