package com.imyeyu.fx.ui;

import com.imyeyu.fx.utils.screen.Screens;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.control.Label;
import javafx.stage.Popup;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.util.List;

/**
 * @author 夜雨
 * @version 2024-04-13 22:40
 */
public class ScreenIdentify extends Stage implements TimiFXUI {

	private final BooleanProperty showingIdentify;
	private final ObservableList<Identify> showingIdentifyList;

	public ScreenIdentify() {

		showingIdentifyList = FXCollections.observableArrayList();

		showingIdentify = new SimpleBooleanProperty(false);
		showingIdentify.bind(Bindings.isEmpty(showingIdentifyList));

		initStyle(StageStyle.UTILITY);
		setOpacity(0);
		setWidth(10);
		setHeight(10);
		setX(-20);
		setY(-20);

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

		showingIdentifyList.addListener((ListChangeListener<Identify>) c -> {
			while (c.next()) {
				if (c.wasAdded()) {
					List<? extends Identify> list = c.getAddedSubList();
					for (Identify identify : list) {
						Rectangle2D r2d = identify.screen.getBounds();
						identify.show(this, r2d.getMinX() + 80, r2d.getMinY() + 80);
					}
				}
				if (c.wasRemoved()) {
					List<? extends Identify> list = c.getRemoved();
					for (Identify identify : list) {
						identify.hide();
					}
				}
			}
		});
	}

	/** 显示标识 */
	public void showIdentify() {
		show();

		List<Screen> screens = Screens.all();
		for (int i = 0; i < screens.size(); i++) {
			showingIdentifyList.add(new Identify(screens.get(i), i));
		}
	}

	/** 隐藏标识 */
	public void hideIdentify() {
		showingIdentifyList.clear();
		hide();
	}

	/** @return true 为正在显示标识 */
	public boolean isShowingIdentify() {
		return showingIdentify.get();
	}

	/** @return 正在显示标识监听 */
	public ReadOnlyBooleanProperty showingIdentify() {
		return showingIdentify;
	}

	/**
	 * 屏幕标识
	 *
	 * @author 夜雨
	 * @since 2022-02-17 15:42
	 */
	private static class Identify extends Popup implements TimiFXUI, TimiFXUI.Colorful {

		/** 所属屏幕 */
		final Screen screen;

		public Identify(Screen screen, int i) {
			this.screen = screen;

			Label text = new Label(String.valueOf(i));
			text.setTextFill(WHITE);
			text.setAlignment(Pos.CENTER);
			text.prefHeightProperty().bind(text.widthProperty());
			text.prefWidthProperty().bind(text.heightProperty());
			MinecraftFont.css(text, 256);

			getContent().setAll(text);
			getScene().setFill(BLACK);
			TimiFXUI.applyStyle(getScene());
			sizeToScene();
		}
	}
}
