package cn.forevermc.launcher.view.components;

import cn.forevermc.launcher.bean.LaunchGame;
import cn.forevermc.launcher.bean.Page;
import cn.forevermc.launcher.service.BGService;
import cn.forevermc.launcher.service.PageService;
import cn.forevermc.launcher.util.Resources;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.event.EventHandler;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import com.imyeyu.fx.utils.BgImage;
import com.imyeyu.inject.annotation.Component;
import com.imyeyu.inject.annotation.Inject;
import com.imyeyu.inject.annotation.InvokeForInjected;

/**
 * 根布局
 *
 * @author 夜雨
 * @since 2022-11-21 16:39
 */
@Component
public class RootLayout extends StackPane {

	@Inject
	private BGService bgService;

	@Inject
	private PageService pageService;

	@Inject
	private LaunchGame launchGame;

	private final StackPane bg;
	private final BorderPane main;

	public RootLayout() {
		// 背景面板
		bg = new StackPane();
		bg.setScaleX(1.1);
		bg.setScaleY(1.1);

		main = new BorderPane();
		getChildren().addAll(bg, main);

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

		// 动态背景
		final float bgStep = .1F;
		addEventFilter(MouseEvent.MOUSE_MOVED, new EventHandler<>() {

			// 面板 xy 坐标，旧的鼠标 xy 坐标
			private double pX = 0, pY = 0, moX, moY;

			@Override
			public void handle(MouseEvent event) {
				if (event.getX() < moX && pX < 0) {
					pX += bgStep;
				} else {
					if (moX < event.getX() && -20 < pX) {
						pX -= bgStep;
					}
				}
				if (event.getY() < moY && pY < 0) {
					pY += bgStep;
				} else {
					if (moY < event.getY() && -20 < pY) {
						pY -= bgStep;
					}
				}
				bg.setTranslateX(pX);
				bg.setTranslateY(pY);
				moX = event.getX();
				moY = event.getY();
			}
		});
	}

	@InvokeForInjected
	private void injected() {
		Background legacyBG = new BgImage(Resources.DIRT).build();
		bg.backgroundProperty().bind(Bindings.createObjectBinding(() -> {
			if (launchGame.isNewUI()) {
				return bgService.getValue();
			}
			if (pageService.getActivatedPage() == Page.MENU) {
				return bgService.getValue();
			}
			return legacyBG;
		}, launchGame.newUIProperty(), pageService.activatedPageProperty()));
		BooleanBinding withOutBlur = pageService.activatedPageProperty().isEqualTo(Page.MENU).or(launchGame.newUIProperty().not());
		bg.effectProperty().bind(Bindings.when(withOutBlur).then((GaussianBlur) null).otherwise(new GaussianBlur(16)));
	}

	public void setPage(AbstractPane page) {
		main.setCenter(page);
	}
}
