package cn.forevermc.launcher.ctrl.pane;

import cn.forevermc.launcher.bean.Game;
import cn.forevermc.launcher.bean.Page;
import cn.forevermc.launcher.service.PageService;
import cn.forevermc.launcher.util.Path;
import cn.forevermc.launcher.view.pages.OriginalSelectPane;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.imyeyu.fx.task.RunAsync;
import com.imyeyu.fx.ui.TimiFXUI;
import com.imyeyu.inject.annotation.Controller;
import com.imyeyu.inject.annotation.Inject;
import com.imyeyu.inject.annotation.SuperInject;
import com.imyeyu.io.IO;
import com.imyeyu.java.ref.Ref;
import com.imyeyu.network.FileRequest;
import com.imyeyu.network.GsonRequest;
import com.imyeyu.utils.OS;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 原版选择
 *
 * @author 夜雨
 * @since 2022-11-28 15:43
 */
@Slf4j
@Controller
@SuperInject
public class OriginalSelect extends OriginalSelectPane implements OS.FileSystem {

	/** 列表接口 */
	private static final String API_LIST = "https://launchermeta.mojang.com/mc/game/version_manifest.json";

	@Inject
	private Dialog dialog;

	@Inject
	private PageService pageService;

	public OriginalSelect() {
		// 下载
		download.setOnAction(e -> {
			Game game = list.getSelectionModel().getSelectedItem();

			dialog.setContent(TimiFXUI.MULTILINGUAL.text("downloading"));
			dialog.eject();

			new RunAsync<String>() {

				@Override
				protected String call() throws Exception {
					File dir = IO.dir(Path.P_PACK + game.getId());
					Thread.sleep(500);
					FileRequest.get(game.getUrl()).toFile(IO.file(dir.getAbsolutePath() + SEP + game.getId() + ".json"));
					return null;
				}

				@Override
				protected void onFinish() {
					pageService.to(Page.GAME_SELECT);
				}

				@Override
				protected void onException(Throwable e) {
					dialog.setContent(TimiFXUI.MULTILINGUAL.textArgs("fmc.launcher.download.mojang.download_error", e.getMessage()));
					dialog.setCloseEvent(() -> pageService.to(Page.ORIGINAL_SELECT));
					dialog.eject();
					log.error("download game error", e);
				}
			}.start();
		});

		// 返回
		back.setOnAction(e -> pageService.to(Page.GAME_SELECT));
	}


	@Override
	public void onShow() {
		list.getSelectionModel().clearSelection();
		if (list.getItems().isEmpty()) {
			setLoading(true);
			new RunAsync<List<Game>>() {

				@Override
				protected List<Game> call() throws Exception {
					List<Game> result = new ArrayList<>();

					JsonObject root = GsonRequest.get(API_LIST).asJsonObject();

					JsonArray array = root.get("versions").getAsJsonArray();
					JsonObject jo;
					Game.Type type;
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
					for (int i = 0; i < array.size(); i++) {
						jo = array.get(i).getAsJsonObject();
						type = Ref.toType(Game.Type.class, jo.get("type").getAsString());
						if (type == Game.Type.RELEASE) {
							Game game = new Game();
							game.setId(jo.get("id").getAsString());
							game.setType(type);
							game.setUrl(jo.get("url").getAsString());
							game.setReleaseAt(dateFormat.parse(jo.get("releaseTime").getAsString()).getTime());
							result.add(game);
						}
					}
					return result;
				}

				@Override
				protected void onFinish(List<Game> result) {
					list.getItems().setAll(result);
				}

				@Override
				protected void onException(Throwable e) {
					dialog.setContent(TimiFXUI.MULTILINGUAL.text("fmc.launcher.download.mojang.api_error"));
					dialog.setCloseEvent(() -> pageService.to(Page.GAME_SELECT));
					dialog.eject();
				}

				@Override
				protected void onFinally() {
					setLoading(false);
				}
			}.start();
		}
		list.scrollTo(0);
	}
}
