package de.retest.recheck;

import java.io.IOException;
import java.util.prefs.Preferences;

import org.keycloak.adapters.ServerRequest.HttpFailure;
import org.keycloak.common.VerificationException;

import de.retest.recheck.Properties.FileOutputFormat;
import de.retest.recheck.auth.RehubAuthenticationHandler;
import de.retest.recheck.auth.RetestAuthentication;
import de.retest.recheck.persistence.CloudPersistence;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Rehub {

	private Rehub() {

	}

	/**
	 * Initializes rehub to be used as persistence and, if not already authenticated, asks for login.
	 */
	public static void init() {
		System.setProperty( RetestAuthentication.RESOURCE_PROPERTY, "marvin" );

		final RetestAuthentication auth = RetestAuthentication.getInstance();

		try {
			if ( !auth.isAuthenticated( getToken() ) ) {
				auth.login( new RehubAuthenticationHandler() );
			}
			System.setProperty( Properties.FILE_OUTPUT_FORMAT_PROPERTY, FileOutputFormat.CLOUD.toString() );
		} catch ( IOException | HttpFailure | VerificationException e ) {
			log.error( "Error verifying offline token", e );
		}
	}

	private static String getToken() {
		final String tokenFromEnvironment = System.getenv( CloudPersistence.RECHECK_API_KEY );
		final String tokenFromPreferences =
				Preferences.userNodeForPackage( Rehub.class ).get( CloudPersistence.RECHECK_API_KEY, null );

		return tokenFromEnvironment != null ? tokenFromEnvironment : tokenFromPreferences;
	}

}

@@ -828,21 +828,29 @@
 ted( get
-Token
+RecheckApiKey
 () ) ) %7B
@@ -1136,23 +1136,247 @@
 %09%7D%0A%09%7D%0A%0A%09
-private
+/**%0A%09 * Returns the given recheck API key for rehub.%0A%09 *%0A%09 * %3Cp%3E%0A%09 * %3Cem%3ETreat this as a secret! Anyone with access to your token can add test reports to rehub.%3C/em%3E%0A%09 *%0A%09 * @return The given recheck API key for rehub.%0A%09 */%0A%09public
  static 
@@ -1389,13 +1389,21 @@
  get
-Token
+RecheckApiKey
 () %7B

Allow users to access their API keys