package com.imyeyu.fx.ui.examples.component;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.imyeyu.fx.task.RunAsync;
import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.fx.ui.components.VersionLabel;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import org.apache.hc.client5.http.fluent.Request;

/**
 * Timi 通用版本标签
 *
 * @author 夜雨
 * @since 2022-05-31 23:24
 */
public class TimiVersionLabel extends VersionLabel<JsonObject> {

	private final String nowVersion;
	private final String appName;

	public TimiVersionLabel(String nowVersion, String appName) {
		super(TimiFXUI.MULTILINGUAL.text("version.checking"));

		this.nowVersion = nowVersion;
		this.appName = appName;

		RunAsync.later(() -> checkVersion(nowVersion), 2000);
	}

	@Override
	protected JsonObject run() {
		try {
			Thread.sleep(2000);
			String api = "https://api.imyeyu.com/versions/" + appName;
			return JsonParser.parseString(Request.get(api).execute().returnContent().asString()).getAsJsonObject();
		} catch (Exception e) {
			throw new TimiException(TimiCode.ERROR, e.getMessage());
		}
	}

	@Override
	protected String onReturn(JsonObject resp) {
		int code = resp.get("code").getAsInt();
		if (code == 20000) {
			JsonObject data = resp.get("data").getAsJsonObject();
			setUpdateURL(data.get("url").getAsString());
			if (data.has("content") && TimiJava.isNotEmpty(data.get("content").getAsString())) {
				content.setText(data.get("content").getAsString());
			}
			return data.get("version").getAsString();
		} else {
			throw new TimiException(TimiCode.fromCode(code), resp.get("msg").getAsString());
		}
	}

	@Override
	protected String updateText(String newVersion) {
		return TimiFXUI.MULTILINGUAL.text("version.new");
	}

	@Override
	protected String failText(Throwable e) {
		return TimiFXUI.MULTILINGUAL.text("version.fail");
	}
}
