package com.imyeyu.fx.ui.components;

import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.java.TimiJava;
import com.imyeyu.utils.Encoder;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 超链标签
 *
 * <pre>
 *     new Hyperlink("个人博客", "<a href="https://www.imyeyu.net">https://www.imyeyu.net</a>");
 * </pre>
 *
 * @author 夜雨
 * @since 2022-08-30 10:51
 */
public class Hyperlink extends Label implements TimiFXUI, TimiFXUI.Colorful {

	private static final String STYLE_CLASS = "x-hyperlink";
	private static final Pattern URL_PATTERN = Pattern.compile("https?://(www\\.)?[-a-zA-Z\\d@:%._+~#=]{1,256}\\.[a-zA-Z\\d()]{1,6}\\b([-a-zA-Z\\d()@:%_+.~#?&/=]*)");

	/** 链接监听 */
	protected final StringProperty url;

	/** 默认构造器 */
	public Hyperlink() {
		this("", "");
	}

	/**
	 * 构造器，链接和文本一致
	 *
	 * @param url 链接
	 */
	public Hyperlink(String url) {
		this(url, url);
	}

	/**
	 * 构造器
	 *
	 * @param text 显示文本
	 * @param url  链接
	 */
	public Hyperlink(String text, String url) {
		this(null, text, url);
	}

	/**
	 * 构造器
	 *
	 * @param icon 显示图标
	 * @param text 显示文本
	 * @param url  链接
	 */
	public Hyperlink(Node icon, String text, String url) {
		super(text);

		this.url = new SimpleStringProperty(url);

		getStyleClass().add(STYLE_CLASS);
		setCursor(Cursor.HAND);
		setGraphic(icon);

		addEventFilter(MouseEvent.MOUSE_CLICKED, e -> {
			if (e.getButton() == MouseButton.PRIMARY) {
				if (TimiJava.isNotEmpty(this.url.get())) {
					Matcher matcher = URL_PATTERN.matcher(this.url.get());
					if (matcher.find()) {
						try {
							Desktop dp = Desktop.getDesktop();
							if (dp.isSupported(Desktop.Action.BROWSE)) {
								dp.browse(URI.create(Encoder.url(this.url.get())));
							}
						} catch (IOException ex) {
							ex.printStackTrace();
						}
					}
				}
			}
		});
	}

	/**
	 * 同步设置链接和文本
	 *
	 * @param textUrl 显示文本和链接
	 */
	public void sync(String textUrl) {
		setText(textUrl);
		url.set(textUrl);
	}

	/**
	 * 获取当前链接
	 *
	 * @return 链接
	 */
	public String getUrl() {
		return url.get();
	}

	/**
	 * 设置链接
	 *
	 * @param url 链接
	 */
	public void setUrl(String url) {
		this.url.set(url);
	}

	/**
	 * 获取链接监听
	 *
	 * @return 链接监听
	 */
	public StringProperty urlProperty() {
		return url;
	}

	@Override
	public String getUserAgentStylesheet() {
		return Hyperlink.class.getResource(RESOURCE + "style/components/hyperlink.css").toExternalForm();
	}
}
