package org.kar.karusic;

import java.util.List;
import java.util.logging.LogManager;

import org.kar.archidata.api.DataResource;
import org.kar.archidata.api.ProxyResource;
import org.kar.archidata.exception.DataAccessException;
import org.kar.archidata.externalRestApi.AnalyzeApi;
import org.kar.archidata.externalRestApi.TsGenerateApi;
import org.kar.archidata.tools.ConfigBaseVariable;
import org.kar.karusic.api.AlbumResource;
import org.kar.karusic.api.ArtistResource;
import org.kar.karusic.api.Front;
import org.kar.karusic.api.GenderResource;
import org.kar.karusic.api.HealthCheck;
import org.kar.karusic.api.PlaylistResource;
import org.kar.karusic.api.TrackResource;
import org.kar.karusic.api.UserResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;

public class WebLauncherLocal extends WebLauncher {
	private static final Logger LOGGER = LoggerFactory.getLogger(WebLauncherLocal.class);

	private WebLauncherLocal() {}

	public static void generateObjects() throws Exception {
		LOGGER.info("Generate APIs");
		final List<Class<?>> listOfResources = List.of(AlbumResource.class, ArtistResource.class, Front.class, GenderResource.class, HealthCheck.class, PlaylistResource.class, UserResource.class,
				TrackResource.class, DataResource.class, ProxyResource.class);
		final AnalyzeApi api = new AnalyzeApi();
		api.addAllApi(listOfResources);
		TsGenerateApi.generateApi(api, "../front/src/back-api/");
		LOGGER.info("Generate APIs (DONE)");
	}

	public static void main(final String[] args) throws Exception {
		// Loop-back of logger JDK logging API to SLF4J
		LogManager.getLogManager().reset();
		SLF4JBridgeHandler.install();
		// Generate the APIs in type-script
		generateObjects();
		final WebLauncherLocal launcher = new WebLauncherLocal();
		launcher.process();
		launcher.LOGGER.info("end-configure the server & wait finish process:");
		Thread.currentThread().join();
		launcher.LOGGER.info("STOP the REST server:");
	}

	@Override
	public void process() throws InterruptedException, DataAccessException {
		if (true) {
			// for local test:
			ConfigBaseVariable.apiAdress = "http://0.0.0.0:19080/karusic/api/";
			// ConfigBaseVariable.ssoAdress = "https://atria-soft.org/karso/api/";
			ConfigBaseVariable.dbPort = "3906";
			ConfigBaseVariable.testMode = "true";
		}
		try {
			super.migrateDB();
		} catch (final Exception e) {
			e.printStackTrace();
			while (true) {
				LOGGER.error("============================================================================");
				LOGGER.error("== Migration fail ==> waiting intervention of administrator...");
				LOGGER.error("============================================================================");
				Thread.sleep(60 * 60 * 1000);
			}
		}
		super.process();
	}
}
