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

import cn.forevermc.launcher.util.Sound;
import javafx.beans.binding.Bindings;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.Skin;
import javafx.scene.control.skin.TextFieldSkin;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.Border;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import com.imyeyu.fx.ui.MinecraftFont;
import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.fx.utils.BgFill;
import com.imyeyu.fx.utils.BorderStroke;
import com.imyeyu.java.ref.Ref;

/**
 * MC 密码输入框
 *
 * @author 夜雨
 * @since 2022-11-23 00:27
 */
public class MCPasswordField extends PasswordField implements TimiFXUI {

	private static final Border BORDER_FOCUSED = new BorderStroke(Colorful.WHITE).width(2).build();
	private static final Border BORDER_DEFAULT = new BorderStroke("#A0A0A0").width(2).build();
	private static final Background BG = new BgFill("#000D").build();
	private static final Background BG_DISABLED = new BgFill("#444C").build();

	private final Label label;

	public MCPasswordField() {
		label = new Label();
		label.setTextFill(Colorful.LIGHT_GRAY);
		label.translateXProperty().bind(label.widthProperty().negate().subtract(4));

		getStyleClass().setAll("mc-text-field");
		setFont(MinecraftFont.X16());
		borderProperty().bind(Bindings.when(focusedProperty()).then(BORDER_FOCUSED).otherwise(BORDER_DEFAULT));
		paddingProperty().bind(Bindings.createObjectBinding(() -> new Insets(8, 0, 8, label.getWidth() + 8), label.widthProperty()));
		backgroundProperty().bind(Bindings.when(disabledProperty()).then(BG_DISABLED).otherwise(BG));
		addEventFilter(MouseEvent.MOUSE_PRESSED, e -> Sound.CLICK.play());
	}

	@Override
	protected Skin<?> createDefaultSkin() {
		Skin<?> skin = super.createDefaultSkin();
		if (skin instanceof TextFieldSkin textFieldSkin) {
			try {
				Pane textGroup = Ref.getFieldValue(textFieldSkin, "textGroup", Pane.class);

				StackPane root = new StackPane();
				StackPane.setAlignment(label, Pos.CENTER_LEFT);
				root.getChildren().addAll(label, textGroup);

				textFieldSkin.getChildren().setAll(root);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		}
		return skin;
	}

	/** @return 标签 */
	public String getLabel() {
		return label.getText();
	}

	/** @param label 设置标签 */
	public void setLabel(String label) {
		this.label.setText(label);
	}

	/** @return 标签监听 */
	public StringProperty labelProperty() {
		return label.textProperty();
	}
}
