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

import com.google.auto.service.AutoService;
import org.jboss.installer.core.InstallationData;
import org.jboss.installer.postinstall.PostInstallTask;
import org.jboss.installer.postinstall.SimplePostInstallTask;
import org.jboss.installer.postinstall.TaskPrinter;

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 static org.jboss.installer.core.LoggerUtils.taskLog;
import static org.jboss.installer.postinstall.task.PortConfigurationTask.DOMAIN_MANAGEMENT_HTTPS_PORT_DEFAULT;
import static org.jboss.installer.postinstall.task.PortConfigurationTask.DOMAIN_MANAGEMENT_PORT_DEFAULT;

@AutoService(PostInstallTask.class)
public class JBossCliPortUpdaterTask implements SimplePostInstallTask {

    private static final String NAME_KEY = "postinstall.title.sslcli";

    @Override
    public String getName() {
        return NAME_KEY;
    }

    @Override
    public String getSerializationName() {
        return "change-ports-scripts";
    }

    @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 PortConfigurationTask.Config portConfig = idata.getConfig(PortConfigurationTask.Config.class);
        final boolean enableHttps = idata.getConfig(HttpsEnableTask.Config.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(PortConfigurationTask.Config 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;
    }

    private void doReplace(Path configFilePath, String text, String rep) throws IOException {
        final List<String> lines = Files.readAllLines(configFilePath);
        try (final PrintWriter writer = new PrintWriter(new FileWriter(configFilePath.toFile()))) {
            lines.stream()
                    .map(l -> replace(l, text, rep))
                    .forEach(l -> writer.println(l));
        }
    }
}
