/*
 * Copyright (c) 2016-2017, Adam <Adam@sigterm.info>
 * Copyright (c) 2018, Tomas Slusny <slusnucky@gmail.com>
 * Copyright (c) 2019 Abex
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package net.runelite.client.rs;
import java.applet.Applet;
import java.io.IOException;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.swing.SwingUtilities;
import lombok.extern.slf4j.Slf4j;
import net.runelite.client.RuneLiteProperties;
import net.runelite.client.RuntimeConfig;
import net.runelite.client.RuntimeConfigLoader;
import static net.runelite.client.rs.ClientUpdateCheckMode.MAPPED;
import static net.runelite.client.rs.ClientUpdateCheckMode.NONE;
import net.runelite.client.ui.FatalErrorDialog;
import net.runelite.client.ui.SplashScreen;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;

@Slf4j
@SuppressWarnings({"deprecation", "removal"})
public class ClientLoader implements Supplier<Applet> {
	private static final int NUM_ATTEMPTS = 6;
	private final ClientConfigLoader clientConfigLoader;
	private ClientUpdateCheckMode updateCheckMode;
	private final WorldSupplier worldSupplier;
	private final RuntimeConfigLoader runtimeConfigLoader;
	private final String javConfigUrl;

	private Object client;

	public ClientLoader(OkHttpClient okHttpClient, ClientUpdateCheckMode updateCheckMode, RuntimeConfigLoader runtimeConfigLoader, String javConfigUrl) {
		this.clientConfigLoader = new ClientConfigLoader(okHttpClient);
		this.updateCheckMode = updateCheckMode;
		this.worldSupplier = new WorldSupplier(okHttpClient);
		this.runtimeConfigLoader = runtimeConfigLoader;
		this.javConfigUrl = javConfigUrl;
	}

	@Override
	public synchronized Applet get() {
		if (client == null) {
			client = doLoad();
		}

		if (client instanceof Throwable) {
			throw new RuntimeException((Throwable) client);
		}
		return (Applet) client;
	}

	private Object doLoad() {
		if (updateCheckMode == NONE) {
			return null;
		}

		try {
			SplashScreen.stage(0, null, "Fetching applet viewer config");
			RSConfig config = downloadConfig();

			SplashScreen.stage(.05, null, "Waiting for other clients to start");

			if (updateCheckMode == MAPPED) {
				SplashScreen.stage(.465, "Starting", "Starting Ash");

				Applet rs = loadMappedClient(config);

				SplashScreen.stage(.5, null, "Starting core classes");

				return rs;
			}
		} catch (OutageException e) {
			return e;
		} catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException
				 | SecurityException e) {
			log.error("Error loading RS!", e);

			if (!checkOutages()) {
				SwingUtilities.invokeLater(() -> FatalErrorDialog.showNetErrorWindow("loading the client", e));
			}
			return e;
		}
		return null;
	}

	private Applet loadMappedClient(RSConfig config) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
		Class<?> clientClass = mapped.Client.class;

		Applet rs = (Applet) clientClass.newInstance();
		rs.setStub(new RSAppletStub(config, runtimeConfigLoader));

		return rs;
	}

	private RSConfig downloadConfig() throws IOException {
		for (int attempt = 0; attempt < NUM_ATTEMPTS; attempt++) {
			HttpUrl url = HttpUrl.get(javConfigUrl);
			try {
				return clientConfigLoader.fetch(url);
			} catch (IOException e) {
				SplashScreen.stage(0, null,  "(" + attempt + ")" + " Attempting to fetch again...");
				log.info("Failed to get jav_config from host \"{}\" ({})", url.host(), e.getMessage());
			}
		}

		log.info("Falling back to backup client config");

		try {
			return downloadFallbackConfig();
		} catch (IOException ex) {
			log.debug("error downloading backup config", ex);
		}
		return null;
	}

	@Nonnull
	private RSConfig downloadFallbackConfig() throws IOException {
		return clientConfigLoader.fetch(HttpUrl.get(RuneLiteProperties.getJavConfigBackup()));
	}

	private static class OutageException extends RuntimeException {
		private OutageException(Throwable cause) {
			super(cause);
		}
	}

	private boolean checkOutages() {
		RuntimeConfig rtc = runtimeConfigLoader.tryGet();
		if (rtc != null) {
			return rtc.showOutageMessage();
		}
		return false;
	}
}
