package cn.forevermc.launcher.view.components;

import cn.forevermc.launcher.util.Resources;
import com.google.gson.JsonObject;
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 com.imyeyu.network.GsonRequest;
import lombok.extern.slf4j.Slf4j;

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

	private final String nowVersion, appName;

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

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

		Status.NORMAL.setTextColor(WHITE);
		version.setEffect(Resources.TEXT_SHADOW);
		RunAsync.later(() -> checkVersion(nowVersion), 2000);
	}

	@Override
	protected JsonObject run() {
		try {
			Thread.sleep(2000);
			log.info("checking version..");
			String api = Resources.TIMI_SERVER_API + "/versions/" + appName;
			return GsonRequest.get(api).asJsonObject();
		} 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")) {
				String content = data.get("content").getAsString();
				if (TimiJava.isNotEmpty(content)) {
					this.content.setText(content);
				}
			}
			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.textArgs("version.new", nowVersion, newVersion);
	}

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