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

import org.jboss.installer.core.InstallationData;
import org.jboss.installer.postinstall.TaskPrinter;
import org.jboss.installer.postinstall.server.DomainServer;
import org.jboss.installer.postinstall.server.StandaloneServer;
import org.jboss.installer.postinstall.task.NoopPrinter;
import org.jboss.installer.postinstall.task.PortBindingConfig;
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.XPathFactory;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class PortConfigurationTaskTest {

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

    @Rule
    public TemporaryFolder temp = new TemporaryFolder();

    private XPath xPath =  XPathFactory.newInstance().newXPath();
    private DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    private DocumentBuilder builder;
    private static Map<String, List<String>> expectedConfigs;
    private static Map<String, String> expectedPorts;
    private TaskPrinter printer = new NoopPrinter();

    static {
        expectedConfigs = new HashMap<>();
        expectedConfigs.put("host.xml", Arrays.asList("server-one", "server-two", "server-three"));
        expectedConfigs.put(DomainServer.HOST_SECONDARY_XML, Arrays.asList("server-one", "server-two"));
        expectedConfigs.put(DomainServer.HOST_PRIMARY_XML, Collections.EMPTY_LIST);
        expectedPorts = new HashMap<>();
        expectedPorts.put("server-one", "100");
        expectedPorts.put("server-two", "250");
        expectedPorts.put("server-three", "350");
    }

    @Before
    public void setUp() throws Exception {
        builder = factory.newDocumentBuilder();
    }

    @Test
    public void setPortOffsetInStandaloneConfig() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        idata.putConfig(new PortBindingConfig(100));
        final StandaloneServer srv = new StandaloneServer(TestServer.TARGET_PATH);

        try {
            srv.start("standalone.xml");
            new PortConfigurationTask().applyToStandalone(idata, srv, printer);

            assertDefaultOffsetChanged("standalone.xml");
        } finally {
            srv.shutdown();
        }
    }

    @Test
    public void setPortOffsetInDomainHostConfig() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        idata.putConfig(new PortBindingConfig(100));
        final DomainServer srv = new DomainServer(TestServer.TARGET_PATH);

        try {
            srv.start("host.xml");
            new PortConfigurationTask().applyToDomain(idata, srv, printer);

            assertDefaultOffsetChanged("host.xml");
            assertManagementInterfacePortChanged("host.xml");
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void setPortOffsetInDomainHostSecondaryConfig() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        idata.putConfig(new PortBindingConfig(100));
        final DomainServer srv = new DomainServer(TestServer.TARGET_PATH);

        try {
            srv.start(DomainServer.HOST_SECONDARY_XML);
            new PortConfigurationTask().applyToDomain(idata, srv, printer);

            assertDefaultOffsetChanged(DomainServer.HOST_SECONDARY_XML);
            assertStaticDiscoveryPortChanged(DomainServer.HOST_SECONDARY_XML);
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void setPortOffsetInDomainHostPrimaryConfig() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        idata.putConfig(new PortBindingConfig(100));
        final DomainServer srv = new DomainServer(TestServer.TARGET_PATH);

        try {
            srv.start(DomainServer.HOST_PRIMARY_XML);
            new PortConfigurationTask().applyToDomain(idata, srv, printer);

            assertDefaultOffsetChanged(DomainServer.HOST_PRIMARY_XML);
            assertManagementInterfacePortChanged("host.xml");
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void setHttpPortInStandaloneXml() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        final PortBindingConfig config = new PortBindingConfig(0);
        config.setPorts("standalone.xml", Arrays.asList(new PortBindingConfig.SocketBinding("http", "jboss.http.port", 8081)));
        idata.putConfig(config);

        final StandaloneServer srv = new StandaloneServer(TestServer.TARGET_PATH);

        try {
            srv.start("standalone.xml");
            new PortConfigurationTask().applyToStandalone(idata, srv, printer);

            assertSocketBinding("standalone.xml", "standard-sockets", "http", "${jboss.http.port:8081}");
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void dontSetPropertyIfNotPresent() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        final PortBindingConfig config = new PortBindingConfig(0);
        config.setPorts("standalone.xml", Arrays.asList(new PortBindingConfig.SocketBinding("http", null, 8081)));
        idata.putConfig(config);

        final StandaloneServer srv = new StandaloneServer(TestServer.TARGET_PATH);

        try {
            srv.start("standalone.xml");
            new PortConfigurationTask().applyToStandalone(idata, srv, printer);

            assertSocketBinding("standalone.xml", "standard-sockets", "http", "8081");
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void setMulticastPortInStandaloneHaXml() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        final PortBindingConfig config = new PortBindingConfig(0);
        config.setPorts("standalone-ha.xml", Arrays.asList(
                new PortBindingConfig.SocketBinding("jgroups-udp", "jboss.default.multicast.address",
                        "230.0.0.5", 45689, 55201)));
        idata.putConfig(config);

        final StandaloneServer srv = new StandaloneServer(TestServer.TARGET_PATH);

        try {
            srv.start("standalone-ha.xml");
            new PortConfigurationTask().applyToStandalone(idata, srv, printer);

            assertMulticastBinding("standalone-ha.xml",
                    "jgroups-udp", "${jboss.default.multicast.address:230.0.0.5}", "45689", "55201");
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void setStandardSocketsInDomainXml() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        final PortBindingConfig config = new PortBindingConfig(0);
        config.setPorts("domain-standard", Arrays.asList(
                        new PortBindingConfig.SocketBinding("http", "jboss.http.port", 8081)));
        idata.putConfig(config);

        final DomainServer srv = new DomainServer(TestServer.TARGET_PATH);

        try {
            srv.start("host.xml");
            new PortConfigurationTask().applyToDomain(idata, srv, printer);

            assertSocketBinding("domain.xml", "standard-sockets", "http", "${jboss.http.port:8081}");
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void doNotSetStandardSocketsInDomainHostSecondaryXml() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        final PortBindingConfig config = new PortBindingConfig(0);
        config.setPorts("domain-standard", Arrays.asList(
           new PortBindingConfig.SocketBinding("http", "jboss.http.port", 8081)));
        idata.putConfig(config);

        final DomainServer srv = new DomainServer(TestServer.TARGET_PATH);

        try {
            srv.start(DomainServer.HOST_SECONDARY_XML);
            assertTrue(new PortConfigurationTask().applyToDomain(idata, srv, printer));
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void setHaSocketsInDomainXml() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        final PortBindingConfig config = new PortBindingConfig(0);
        config.setPorts("domain-ha", Arrays.asList(
                new PortBindingConfig.SocketBinding("http", "jboss.http.port", 8081)));
        idata.putConfig(config);

        final DomainServer srv = new DomainServer(TestServer.TARGET_PATH);

        try {
            srv.start("host.xml");
            new PortConfigurationTask().applyToDomain(idata, srv, printer);

            assertSocketBinding("domain.xml", "ha-sockets", "http", "${jboss.http.port:8081}");
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void setDomainManagerSocketInHostXml() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        final PortBindingConfig config = new PortBindingConfig(0);
        config.setManagementInterfacePort(new PortBindingConfig.SocketBinding(null, "jboss.management.http.port", 10090));
        idata.putConfig(config);

        final DomainServer srv = new DomainServer(TestServer.TARGET_PATH);

        try {
            srv.start("host.xml");
            new PortConfigurationTask().applyToDomain(idata, srv, printer);

            assertManagementInterfacePortChanged("host.xml");
        }finally {
            srv.shutdown();
        }
    }

    @Test
    public void setStaticDiscoverySocketInHostSecondaryXml() throws Exception {
        final InstallationData idata = new InstallationData();
        idata.setTargetFolder(TestServer.TARGET_PATH);
        final PortBindingConfig config = new PortBindingConfig(0);
        config.setManagementInterfacePort(new PortBindingConfig.SocketBinding(null, "jboss.management.http.port", 10090));
        idata.putConfig(config);

        final DomainServer srv = new DomainServer(TestServer.TARGET_PATH);

        try {
            srv.start(DomainServer.HOST_SECONDARY_XML);
            new PortConfigurationTask().applyToDomain(idata, srv, printer);

            assertStaticDiscoveryPortChanged(DomainServer.HOST_SECONDARY_XML);
        }finally {
            srv.shutdown();
        }
    }

    private void assertMulticastBinding(String configFile, String socketKey, String expectedAddress, String expectedMcastPort, String expectedPort) throws Exception {
        Document doc = builder.parse(TestServer.TARGET_PATH.resolve("standalone").resolve("configuration").resolve(configFile).toFile());
        NodeList portOffset = (NodeList) xPath.compile(String.format("//socket-binding-group[@name=\"standard-sockets\"]/socket-binding[@name=\"%s\"]", socketKey)).evaluate(
                doc, XPathConstants.NODESET);
        final String portValue = portOffset.item(0).getAttributes().getNamedItem("port").getNodeValue();
        final String mcastPortValue = portOffset.item(0).getAttributes().getNamedItem("multicast-port").getNodeValue();
        final String addressValue = portOffset.item(0).getAttributes().getNamedItem("multicast-address").getNodeValue();
        assertEquals(expectedPort, portValue);
        assertEquals(expectedAddress, addressValue);
        assertEquals(expectedMcastPort, mcastPortValue);
    }

    private void assertSocketBinding(String configFile, String socketGroup, String socketKey, String expectedPort) throws Exception {
        final String dir = configFile.startsWith("standalone")?"standalone":"domain";
        Document doc = builder.parse(TestServer.TARGET_PATH.resolve(dir).resolve("configuration").resolve(configFile).toFile());
        NodeList portOffset = (NodeList) xPath.compile(String.format("//socket-binding-group[@name=\"%s\"]/socket-binding[@name=\"%s\"]",
                socketGroup, socketKey)).evaluate(
                doc, XPathConstants.NODESET);
        final String nodeValue = portOffset.item(0).getAttributes().getNamedItem("port").getNodeValue();
        assertEquals(expectedPort, nodeValue);
    }

    private void assertDefaultOffsetChanged(String configFile) throws Exception {
        if (configFile.startsWith("standalone")) {
            Document doc = builder.parse(TestServer.TARGET_PATH.resolve("standalone").resolve("configuration").resolve(configFile).toFile());
            NodeList portOffset = (NodeList) xPath.compile("//socket-binding-group[@name=\"standard-sockets\"]").evaluate(
                    doc, XPathConstants.NODESET);
            final String nodeValue = portOffset.item(0).getAttributes().getNamedItem("port-offset").getNodeValue();
            assertEquals("${jboss.socket.binding.port-offset:" + 100 + "}", nodeValue);
        } else {
            Document doc = builder.parse(TestServer.TARGET_PATH.resolve("domain").resolve("configuration").resolve(configFile).toFile());
            for (String serverConfig : expectedConfigs.get(configFile)) {
                NodeList portOffset = (NodeList) xPath.compile(String.format("//servers/server[@name=\"%s\"]/socket-bindings", serverConfig)).evaluate(
                        doc, XPathConstants.NODESET);
                String nodeValue = portOffset.item(0).getAttributes().getNamedItem("port-offset").getNodeValue();
                assertEquals(expectedPorts.get(serverConfig), nodeValue);
            }
        }
    }

    private void assertManagementInterfacePortChanged(String configFile) throws Exception {
        Document doc = builder.parse(TestServer.TARGET_PATH.resolve("domain").resolve("configuration").resolve(configFile).toFile());
        NodeList port = (NodeList) xPath.compile("//management/management-interfaces/http-interface/socket").evaluate(
                doc, XPathConstants.NODESET);
        final String portValue = port.item(0).getAttributes().getNamedItem("port").getNodeValue();
        assertEquals("${jboss.management.http.port:10090}", portValue);
    }

    private void assertStaticDiscoveryPortChanged(String configFile) throws Exception {
        Document doc = builder.parse(TestServer.TARGET_PATH.resolve("domain").resolve("configuration").resolve(configFile).toFile());
        NodeList port = (NodeList) xPath.compile("//domain-controller/remote/discovery-options/static-discovery").evaluate(
                doc, XPathConstants.NODESET);
        final String portValue = port.item(0).getAttributes().getNamedItem("port").getNodeValue();
        assertEquals("${jboss.domain.primary.port:10090}", portValue);
    }
}
