/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2022 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jboss.installer.test.utils;

import org.apache.commons.io.FileUtils;
import org.jboss.installer.actions.impl.InstallEap;
import org.jboss.installer.core.LanguageUtils;
import org.junit.rules.ExternalResource;

import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collections;

public class TestServer extends ExternalResource {

    public static final Path TARGET_PATH = Paths.get("target/test-server");
    private static final Path BASE_SERVER_PATH = Paths.get("target/base-server");
    private LanguageUtils langUtils = new MockLanguageUtils();

    @Override
    protected void before() throws Throwable {
        if (!BASE_SERVER_PATH.toFile().exists()) {
            final InstallEap installEap = new InstallEap(BASE_SERVER_PATH, evt -> {
                // do nothing
            }, Collections.emptyList(), TestProperties.getTestRepositories(), langUtils);
            installEap.perform(new PropertyChangeSupport(new Object()));
        }

        initializeWorkingServer();
    }

    private void initializeWorkingServer() throws IOException {
        if (TARGET_PATH.toFile().exists()) {
            FileUtils.deleteDirectory(TARGET_PATH.toFile());
        }
        FileUtils.copyDirectory(BASE_SERVER_PATH.toFile(), TARGET_PATH.toFile(), null, true, StandardCopyOption.COPY_ATTRIBUTES);
    }

    @Override
    protected void after() {
        FileUtils.deleteQuietly(TARGET_PATH.toFile());
    }

    public void restoreConfigs() throws IOException {
        FileUtils.deleteDirectory(TARGET_PATH.resolve("standalone").resolve("configuration").toFile());
        FileUtils.copyDirectory(BASE_SERVER_PATH.resolve("standalone").resolve("configuration").toFile(),
                TARGET_PATH.resolve("standalone").resolve("configuration").toFile());

        FileUtils.deleteDirectory(TARGET_PATH.resolve("domain").resolve("configuration").toFile());
        FileUtils.copyDirectory(BASE_SERVER_PATH.resolve("domain").resolve("configuration").toFile(),
                TARGET_PATH.resolve("domain").resolve("configuration").toFile());
    }
}
