/*
 * Copyright 2015-2026 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v2.0 which
 * accompanies this distribution and is available at
 *
 * https://www.eclipse.org/legal/epl-v20.html
 */

package org.junit.platform.reporting.open.xml;

import static org.junit.platform.reporting.open.xml.OpenTestReportGeneratingListener.ENABLED_PROPERTY_NAME;

import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

public class OpenTestReportGenerationSystemPropertyOverride
		implements BeforeTestExecutionCallback, AfterTestExecutionCallback {

	@Override
	public void beforeTestExecution(ExtensionContext context) {
		var oldValue = System.clearProperty(ENABLED_PROPERTY_NAME);
		getStore(context).put(ENABLED_PROPERTY_NAME, oldValue);
	}

	@Override
	public void afterTestExecution(ExtensionContext context) {
		var oldValue = getStore(context).get(ENABLED_PROPERTY_NAME, String.class);
		if (oldValue == null) {
			System.clearProperty(ENABLED_PROPERTY_NAME);
		}
		else {
			System.setProperty(ENABLED_PROPERTY_NAME, oldValue);
		}
	}

	private static ExtensionContext.Store getStore(ExtensionContext context) {
		return context.getStore(
			ExtensionContext.Namespace.create(OpenTestReportGenerationSystemPropertyOverride.class));
	}
}
