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.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Border;
import javafx.scene.layout.StackPane;
import lombok.Getter;
import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.fx.utils.BgImage;
import com.imyeyu.fx.utils.BorderStroke;

/**
 * MC 按钮
 *
 * @author 夜雨
 * @since 2022-11-22 23:05
 */
public class MCButton extends Button 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();

	@Getter
	protected final Label label;
	protected final StackPane root;

	public MCButton() {
		this("");
	}

	public MCButton(String text) {
		this(null, text);
	}

	/**
	 * 默认构造
	 *
	 * @param size 尺寸，为 null 时根据文本自适应
	 * @param text 按钮文本
	 */
	public MCButton(Double size, String text) {
		// 高光
		StackPane light = new StackPane();
		light.setBorder(new BorderStroke(Colorful.WHITE).width(2, 0, 0, 2).build());
		light.setOpacity(.4);
		light.visibleProperty().bind(disabledProperty().not());

		// 阴影
		StackPane dark = new StackPane();
		dark.setBorder(new BorderStroke(Colorful.BLACK).width(0, 2, 3, 0).build());
		dark.setOpacity(.3);
		dark.visibleProperty().bind(disabledProperty().not());

		// 禁用蒙版
		StackPane mark = new StackPane();
		mark.setOpacity(.7);
		mark.visibleProperty().bind(disabledProperty());
		mark.setBackground(BG.BLACK);

		label = new Label(text);
		label.setEffect(Resources.TEXT_SHADOW);
		label.setTextFill(Colorful.WHITE);
		label.setPadding(new Insets(8, 16, 8, 16));

		getStyleClass().clear();
		if (size != null) {
			setPrefWidth(size);
		}
		borderProperty().bind(Bindings.createObjectBinding(() -> {
			if (!isDisabled() && isHover()) {
				return BORDER_WHITE;
			}
			return BORDER_BLACK;
		}, hoverProperty(), disabledProperty()));
		setGraphic(root = new StackPane() {{
			setBackground(new BgImage(Resources.BTN).build());
			getChildren().addAll(light, dark, mark, label);
		}});

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

		textProperty().addListener((obs, o, newText) -> {
			label.setText(newText);
			setText("");
		});

		addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
			if (!isDisabled()) {
				Sound.CLICK.play();
			}
		});
	}
}
