/*
 * 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.task;

import org.jboss.installer.auto.InstallationDataSerializer;
import org.jboss.installer.core.InstallationData;
import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.postinstall.TaskPrinter;
import org.jboss.installer.postinstall.server.DomainServer;
import org.jboss.installer.postinstall.server.StandaloneServer;
import org.jboss.installer.test.utils.MockLanguageUtils;
import org.jboss.installer.test.utils.TestServer;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.nio.file.Path;
import java.util.Optional;

import static org.jboss.installer.test.utils.TestServer.TARGET_PATH;
import static org.junit.Assert.assertEquals;

public class LoggingLevelsTaskTest {

    private static final String ROOT_LEVEL_LOGGER = "DEBUG";
    private static final String CONSOLE_LEVEL_LOGGER = "WARN";
    private XPath xPath =  XPathFactory.newInstance().newXPath();
    private DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    private DocumentBuilder builder;
    private InstallationData iData;
    private StandaloneServer standaloneServer;
    private DomainServer domainServer;
    private LanguageUtils langUtils;
    private TaskPrinter printer = new NoopPrinter();

    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();

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

    @Before
    public void setUp() throws Exception {
        builder = factory.newDocumentBuilder();
        iData = new InstallationData();
        iData.putConfig(new LoggingLevelsTask.Config(ROOT_LEVEL_LOGGER, CONSOLE_LEVEL_LOGGER));
        iData.setTargetFolder(TARGET_PATH);
        standaloneServer = new StandaloneServer(TARGET_PATH);
        domainServer = new DomainServer(TARGET_PATH);
    }

    @Test
    public void rootLevelAndConsoleLevelAreChanged() throws Exception {
        final String config = "standalone.xml";
        try {
            standaloneServer.start(config);

            new LoggingLevelsTask().applyToStandalone(iData, standaloneServer, printer);

            Document doc = builder.parse(TARGET_PATH.resolve("standalone").resolve("configuration").resolve(config).toFile());
            assertEquals(ROOT_LEVEL_LOGGER, getLevel(doc, "//root-logger/level"));
            assertEquals(CONSOLE_LEVEL_LOGGER, getLevel(doc, "//console-handler[@name=\"CONSOLE\"]/level"));

        } finally {
            standaloneServer.shutdown();
        }
    }

    @Test
    public void onlyRootLevelIsChangedInFullHaConfig() throws Exception {
        final String config = "standalone-full-ha.xml";
        try {
            standaloneServer.start(config);

            new LoggingLevelsTask().applyToStandalone(iData, standaloneServer, printer);

            Document doc = builder.parse(TARGET_PATH.resolve("standalone").resolve("configuration").resolve(config).toFile());
            assertEquals(ROOT_LEVEL_LOGGER, getLevel(doc, "//root-logger/level"));
            //assertNodeDoesntExist(doc, "//console-handler[@name=\"CONSOLE\"]/level");

        } finally {
            standaloneServer.shutdown();
        }
    }

    @Test
    public void onlyRootLevelIsChangedInDomainMode() throws Exception {
        final String config = "host.xml";
        try {
            domainServer.start(config);

            new LoggingLevelsTask().applyToDomain(iData, domainServer, printer);

            Document doc = builder.parse(TARGET_PATH.resolve("domain").resolve("configuration").resolve("domain.xml").toFile());
            for (String profile : DomainServer.PROFILES) {
                String prefix = String.format("//profile[@name=\"%s\"]/subsystem/", profile);

                assertEquals(ROOT_LEVEL_LOGGER, getLevel(doc, prefix + "/root-logger/level"));
                assertNodeDoesntExist(doc, prefix + "/console-handler[@name=\"CONSOLE\"]/level");
            }

        } finally {
            domainServer.shutdown();
        }
    }

    @Test
    public void testSerializeConfig() throws Exception {
        final LoggingLevelsTask.Config config = new LoggingLevelsTask.Config("DEBUG", "INFO");
        iData.putConfig(config);

        final InstallationDataSerializer serializer = new InstallationDataSerializer(new MockLanguageUtils());
        final Path outputFile = tempFolder.newFile().toPath();
        serializer.serialize(iData, outputFile);

        final LoggingLevelsTask.Config deserializedConfig = serializer.deserialize(outputFile, Optional.empty()).getConfig(LoggingLevelsTask.Config.class);

        assertEquals(config, deserializedConfig);
    }

    private void assertNodeDoesntExist(Document doc, String xpath) throws XPathExpressionException {
        assertEquals(0, ((NodeList) xPath.compile(xpath).evaluate(
                doc, XPathConstants.NODESET)).getLength());
    }

    private String getLevel(Document doc, String expression) throws XPathExpressionException {
        NodeList consoleLoggerLevel = (NodeList) xPath.compile(expression).evaluate(
                doc, XPathConstants.NODESET);
        return consoleLoggerLevel.item(0).getAttributes().getNamedItem("name").getNodeValue();
    }
}
