package com.imyeyu.fx.ui.examples.view.pages;

import com.imyeyu.fx.task.RunAsyncScheduled;
import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.fx.ui.components.TextAreaEditor;
import com.imyeyu.fx.ui.examples.component.AbstractDemoPane;
import com.imyeyu.fx.ui.examples.component.sidebar.SidebarItem;
import com.imyeyu.inject.annotation.Component;
import com.imyeyu.utils.Time;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.util.Duration;

/**
 * 异步线程
 *
 * @author 夜雨
 * @since 2022-09-01 14:37
 */
@Component
public class RunAsyncDemo extends AbstractDemoPane {

	public RunAsyncDemo() {
		title.setText(SidebarItem.RUN_ASYNC.getText());
		document.sync("https://doc.imyeyu.net/timi-fx/net/imyeyu/timifx/service/RunAsync.html");
		source.sync("https://git.imyeyu.net/Timi/timi-fx/src/master/src/main/java/net/imyeyu/timifx/service/RunAsync.java");

		Label title = new Label(TimiFXUI.MULTILINGUAL.text("important"));
		title.setTextFill(Colorful.RED);


		// 时间示例
		Label time = new Label();
		RunAsyncScheduled.call(Duration.seconds(1), Time::now, t -> time.setText(Time.toDateTime(t)));

		// 代码示例
		TextAreaEditor code = new TextAreaEditor();
		code.setEditable(false);
		code.setText("""
// 每秒执行一次并返回，参数 3 （FX 线程）的入参是参数 2 （非 FX 线程）的返回
// RunAsyncScheduled.call(Duration.seconds(1), () -> "result", result -> {});

RunAsyncScheduled.call(Duration.seconds(1), () -> {
	long now = System.currentTimeMillis();
	return now;
}, millis -> {
	String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(millis);
	label.setText(datetime);
});
				""".trim());

		setCenter(new BorderPane() {{
			setMargin(code, new Insets(4, 0, 0, 0));
			setPadding(new Insets(20));
			setTop(new VBox() {{
				setMargin(time, new Insets(20, 0, 0, 0));
				setSpacing(4);
				getChildren().addAll(title, time);
			}});
			setCenter(code);
		}});
	}
}
