package cn.forevermc.launcher.service;

import cn.forevermc.launcher.bean.Page;
import cn.forevermc.launcher.view.components.RootLayout;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import lombok.Getter;
import com.imyeyu.inject.annotation.Inject;
import com.imyeyu.inject.annotation.Service;

/**
 * 页面服务
 *
 * @author 夜雨
 * @since 2022-11-21 16:21
 */
@Service
public class PageService {

	@Inject
	private RootLayout root;

	/** 上一页 */
	@Getter
	private Page prev;

	private final ObjectProperty<Page> activatedPage;

	private boolean isSneakyBack;

	public PageService() {
		activatedPage = new SimpleObjectProperty<>();
		activatedPage.addListener((obs, prev, now) -> {
			this.prev = prev;
			if (!isSneakyBack && prev != null) {
				prev.getIOCPage().hide();
			}
			if (now != null) {
				now.getIOCPage().show();
				root.setPage(now.getIOCPage());
			}
			isSneakyBack = false;
		});
	}

	/**
	 * 跳转页面
	 *
	 * @param page 页面
	 */
	public void to(Page page) {
		activatedPage.set(page);
	}

	/** 返回上一个页面 */
	public void back() {
		to(prev);
	}

	/** 悄悄地返回，此动作不会调度页面的 onHide 事件 */
	public void back4Sneaky() {
		isSneakyBack = true;
		back();
	}

	public Page getActivatedPage() {
		return activatedPage.get();
	}

	/** @return 当前页面监听 */
	public ReadOnlyObjectProperty<Page> activatedPageProperty() {
		return activatedPage;
	}
}
