package com.imyeyu.fx.ui.components;

import com.imyeyu.fx.icon.TimiFXIcon;
import com.imyeyu.fx.icon.TimiIcon;
import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.java.bean.CallbackArg;
import com.imyeyu.java.ref.Ref;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Skin;
import javafx.scene.control.skin.TabPaneSkin;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import lombok.Getter;

import java.util.List;

/**
 * 选项卡，简化了选区样式，以及在选项卡右侧添加了新增选项卡按钮，可让用户直接添加
 *
 * @author 夜雨
 * @since 2022-07-24 10:54
 */
@Getter
public class TabPane extends javafx.scene.control.TabPane implements TimiFXUI, TimiFXUI.Colorful {

	@Override
	public String getUserAgentStylesheet() {
		return TabPane.class.getResource(RESOURCE + "style/components/tab-pane.css").toExternalForm();
	}

	@Override
	protected Skin<?> createDefaultSkin() {
		Skin<?> skin = super.createDefaultSkin();
		if (skin instanceof TabPaneSkin tabPaneSkin) {
			try {
				StackPane tabHeaderArea = Ref.getFieldValue(tabPaneSkin, "tabHeaderArea", StackPane.class);
				StackPane headersRegion = Ref.getFieldValue(tabHeaderArea, "headersRegion", StackPane.class);
				Rectangle headerClip = Ref.getFieldValue(tabHeaderArea, "headerClip", Rectangle.class);

				// 关闭按钮调整
				CallbackArg<Node> resizeCloseButton = tabHeaderSkin -> {
					try {
						if (tabHeaderSkin instanceof StackPane tabHeaderPane) {
							StackPane closeBtn = Ref.getFieldValue(tabHeaderSkin, "closeBtn", StackPane.class);
							closeBtn.setPrefWidth(18);
							closeBtn.getStyleClass().clear();

							IconButton icon = new IconButton(TimiFXIcon.get(TimiIcon.FAIL, GRAY));
							icon.setAlignment(Pos.CENTER_LEFT);
							icon.setMouseTransparent(true);
							icon.prefWidthProperty().bind(closeBtn.widthProperty());
							icon.minHeightProperty().bind(tabHeaderPane.heightProperty());
							StackPane.setMargin(icon, new Insets(0, 12, 0, 0));

							closeBtn.getChildren().add(icon);
						}
					} catch (IllegalAccessException e) {
						throw new RuntimeException(e);
					}
				};
				ObservableList<Node> tabList = headersRegion.getChildren();
				for (Node node : tabList) {
					resizeCloseButton.handler(node);
				}
				headersRegion.getChildren().addListener((ListChangeListener<Node>) c -> {
					if (c.next()) {
						List<? extends Node> list = c.getAddedSubList();
						for (Node node : list) {
							resizeCloseButton.handler(node);
						}
					}
				});
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		}
		return skin;
	}
}
