package cn.forevermc.launcher.service;

import cn.forevermc.launcher.bean.APISetting;
import cn.forevermc.launcher.util.Resources;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.imyeyu.fx.task.RunAsync;
import com.imyeyu.inject.annotation.Inject;
import com.imyeyu.inject.annotation.InvokeForInjected;
import com.imyeyu.inject.annotation.Service;
import com.imyeyu.network.TimiRequest;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 夜雨
 * @since 2024-04-29 20:41
 */
@Slf4j
@Service
public class APISettingService {

	private static final String API = Resources.TIMI_SERVER_API + "/setting/map";

	@Inject
	private Gson gson;

	private final ObjectProperty<APISetting> value;

	public APISettingService() {
		value = new SimpleObjectProperty<>();
	}

	@InvokeForInjected
	private void injected() {
		new RunAsync<APISetting>() {

			@Override
			protected APISetting call() throws Exception {
				APISetting setting = new APISetting();
				Map<APISetting.Key, Map<String, Object>> reqArgs = new HashMap<>();
				for (APISetting.Key key : APISetting.Key.values()) {
					reqArgs.put(key, null);
				}
				Map<APISetting.Key, String> data = TimiRequest.<Map<APISetting.Key, String>>wrap(Request.post(API).bodyString(gson.toJson(reqArgs), ContentType.APPLICATION_JSON)).result();
				setting.setBg(gson.fromJson(data.get(APISetting.Key.FMC_BG), APISetting.DynamicList.class));
				setting.setBgm(gson.fromJson(data.get(APISetting.Key.FMC_BGM), APISetting.DynamicList.class));
				setting.setSplashes(gson.fromJson(data.get(APISetting.Key.FMC_SPLASHES), APISetting.DynamicList.class));
				return setting;
			}

			@Override
			protected void onFinish(APISetting setting) {
				APISettingService.this.value.set(setting);
			}

			@Override
			protected void onException(Throwable e) {
				super.onException(e);
			}

		}.start();
	}

	public APISetting getValue() {
		return value.get();
	}

	public ReadOnlyObjectProperty<APISetting> valueProperty() {
		return value;
	}
}
