/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2021 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.postinstall.server;

import org.apache.commons.io.FileUtils;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
import org.jboss.installer.test.utils.TestServer;
import org.junit.ClassRule;
import org.junit.Test;

import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.jboss.as.controller.operations.common.Util.createEmptyOperation;
import static org.jboss.installer.test.utils.TestServer.TARGET_PATH;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

public abstract class AbstractEmbeddedServerTest {

    @ClassRule
    public static TestServer testServer = new TestServer();

    @Test
    public void startServer() throws Exception {
        EmbeddedServer srv = getServer(TARGET_PATH);
        try {
            srv.start(getConfig());

            ModelNode node = srv.execute(createEmptyOperation("product-info", PathAddress.EMPTY_ADDRESS), "");
            assertNotNull(node);
            assertServerMode(node);
        } finally {
            srv.shutdown();
            srv.close();
        }
    }

    protected abstract String getConfig();

    protected abstract void assertServerMode(ModelNode node);

    protected abstract EmbeddedServer getServer(Path targetPath);

    protected abstract List<String> getExpectedConfigurations();

    @Test
    public void failedServerStartThrowsException() throws Exception {
        EmbeddedServer srv = getServer(TARGET_PATH);
        boolean started = false;
        try {
            srv.start("idnotexist");
            started = true;
        } catch(ServerOperationException e) {
            // OK - that's what we expect
        }
        // should not get here, but just in case shutdown
        if (started) {
            srv.shutdown();
            srv.close();
            fail("The server should not have been started started");
        }
    }

    @Test
    public void closeStopsServer() throws Exception {
        try (EmbeddedServer srv = getServer(TARGET_PATH)) {
            srv.start(getConfig());
            srv.shutdown();

            try {
                srv.execute(createEmptyOperation("product-info", PathAddress.EMPTY_ADDRESS), "");
                fail();
            } catch (OperationFailedException e) {
                assertEquals("The connection to the controller has not been established.", e.getCause().getMessage());
            }
        }
    }

    @Test
    public void listsAvailableConfigurations() throws Exception {
        try (EmbeddedServer srv = getServer(TARGET_PATH)) {

            Set<String> configurations = srv.availableConfigurations();

            assertEquals(new HashSet<>(getExpectedConfigurations()), configurations);
        }
    }

    @Test
    public void currentConfigurationReturnLastStartedConfiguration() throws Exception {
        try (EmbeddedServer srv = getServer(TARGET_PATH)) {

            try {
                srv.start(getConfig());
                assertEquals(getConfig(), srv.currentConfiguration());
            } finally {
                srv.shutdown();
            }
        }
    }

    @Test
    public void currentConfigurationReturnNullIfServerIsNotStarted() throws Exception {
        try (EmbeddedServer srv = getServer(TARGET_PATH)) {

            assertNull(srv.currentConfiguration());
        }
    }

    @Test
    public void currentConfigurationReturnNullIfServerWasShutdown() throws Exception {
        try (EmbeddedServer srv = getServer(TARGET_PATH)) {

            try {
                srv.start(getConfig());
            } finally {
                srv.shutdown();
            }

            assertNull(srv.currentConfiguration());
        }
    }

    @Test
    public void startServerInFolderWithSpace() throws Exception {
        final Path testPath = TARGET_PATH.getParent().resolve("test server");
        FileUtils.copyDirectory(TARGET_PATH.toFile(), testPath.toFile());

        EmbeddedServer srv = null;
        try {
            srv = getServer(testPath);
            srv.start(getConfig());
            ModelNode node = srv.execute(createEmptyOperation("product-info", PathAddress.EMPTY_ADDRESS), "");
            assertNotNull(node);
            assertServerMode(node);
        } finally {
            if (srv != null) {
                try {
                    srv.shutdown();
                } catch (Exception e) {
                    // ignore
                }
                srv.close();
            }
            FileUtils.deleteDirectory(testPath.toFile());
        }
    }
}
