/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2024 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 static org.jboss.installer.core.LoggerUtils.taskLog;
import static org.jboss.installer.postinstall.task.impl.PortConfigurationTask.DOMAIN_MANAGEMENT_HTTPS_PORT_DEFAULT;
import static org.jboss.installer.postinstall.task.impl.PortConfigurationTask.DOMAIN_MANAGEMENT_PORT_DEFAULT;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

import org.jboss.installer.core.InstallationData;
import org.jboss.installer.postinstall.SimplePostInstallTaskImpl;
import org.jboss.installer.postinstall.TaskPrinter;
import org.jboss.installer.postinstall.task.AdminHttpsConfig;
import org.jboss.installer.postinstall.task.PortBindingConfig;

class JBossCliPortUpdaterTask implements SimplePostInstallTaskImpl {
    @Override
    public String getName() {
        return "postinstall.title.sslcli";
    }

    @Override
    public boolean applyToInstallation(InstallationData idata, TaskPrinter printer) {
        final Path serverPath = idata.getTargetFolder();
        final Path cliXml = serverPath.resolve("bin").resolve("jboss-cli.xml");

        printer.print("tasks.ports.started", cliXml.toString());

        final PortBindingConfig portConfig = idata.getConfig(PortBindingConfig.class);
        final boolean enableHttps = idata.getConfig(AdminHttpsConfig.class) != null;
        final Optional<Integer> managementPort;
        if (enableHttps) {
            managementPort = getPortConfig(portConfig, "management-https");
        } else {
            managementPort = getPortConfig(portConfig, "management-http");
        }

        final int port = managementPort.orElseGet(()-> {
            final int offset = portConfig==null?0:portConfig.getOffset();
            return (enableHttps? DOMAIN_MANAGEMENT_HTTPS_PORT_DEFAULT:DOMAIN_MANAGEMENT_PORT_DEFAULT) + offset;
        });

        try {
            final List<String> lines = Files.readAllLines(cliXml);
            try (final PrintWriter writer = new PrintWriter(new FileWriter(cliXml.toFile()))) {
                Stream<String> lineStream = lines.stream()
                        .map(l-> replace(l, "<port>9990</port>", "<port>"+port+"</port>"));
                if (enableHttps) {
                    lineStream = lineStream
                            .map(l -> replace(l, "<protocol>remote+http</protocol>", "<protocol>remote+https</protocol>"))
                            .map(l -> replace(l, "remote+http</default-protocol>", "remote+https</default-protocol>"));
                }
                lineStream.forEach(l -> writer.println(l));
            }

        } catch (IOException e) {
            taskLog.error("Error editing " + cliXml, e);
            printer.print("tasks.ports.failed");
            printer.print(e);
            return false;
        }
        printer.print("tasks.ports.finished");
        return true;
    }

    private static Optional<Integer> getPortConfig(PortBindingConfig portConfig, String anObject) {
        if (portConfig == null || portConfig.getPorts("standalone.xml") == null) {
            return Optional.empty();
        }
        return portConfig.getPorts("standalone.xml").stream()
                .filter(s -> s.getKey().equals(anObject))
                .map(s -> s.getPortValue())
                .findFirst();
    }

    private String replace(String l, String s, String s2) {
        return l.contains(s) ? l.replace(s, s2) : l;
    }
}
