/*
 * 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.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.dmr.ModelNode;

import java.io.FileFilter;
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;

public class StandaloneServer extends AbstractEmbeddedServer {

    private static final Set<String> EXCLUDED_CONFIGURATIONS = new HashSet<>();
    private static final String STANDALONE_CONFIG_FILE_PATTERN = "standalone";
    private static final String STANDALONE_FOLDER = "standalone";
    private static final String CONFIGURATION_FOLDER = "configuration";

    static{
        EXCLUDED_CONFIGURATIONS.add("standalone-load-balancer.xml");
    }
    public static final Path CONFIG_DIR = Path.of("standalone", "configuration");

    public StandaloneServer(Path path) {
        super(path);
    }

    @Override
    protected String getStartupCommand() {
        return "embed-server --jboss-home=\"%s\" --server-config=%s";
    }

    @Override
    protected String getShutdownCommand() {
        return "stop-embedded-server";
    }

    @Override
    protected FileFilter getConfigFileFilter() {
        return file -> {
            final String fileName = file.getName();
            return file.isFile() && fileName.startsWith(STANDALONE_CONFIG_FILE_PATTERN) && !EXCLUDED_CONFIGURATIONS.contains(fileName);
        };
    }

    @Override
    protected Path getConfigDirectory() {
        return path.resolve(STANDALONE_FOLDER).resolve(CONFIGURATION_FOLDER);
    }

    @Override
    public boolean isDomain() {
        return false;
    }

    @Override
    public boolean aliasExists(String alias, String storeName) throws OperationFailedException {
        final ModelNode queryAliasOp = createEmptyOperation("read-aliases",
                PathAddress.pathAddress("subsystem", "elytron").append("credential-store", storeName));

        final List<ModelNode> aliases = this.execute(queryAliasOp, "Query aliases").asList();
        for (ModelNode modelNode : aliases) {
            if (alias.matches(modelNode.asString())) {
                return true;
            }
        }

        return false;
    }

    @Override
    public ServerPath toRelativePathNode(Path absolutePath) {
        Path configFolder = getConfigDirectory();
        if (absolutePath.toAbsolutePath().startsWith(configFolder.toAbsolutePath())) {
            final String path = configFolder.relativize(absolutePath).toString();
            final String relativeTo = "jboss.server.config.dir";
            return new ServerPath(relativeTo, path);
        } else {
            return new ServerPath(absolutePath.toAbsolutePath().toString());
        }
    }

    @Override
    public ModelNode encryptPassword(String alias, String storeName, String keystorePassword) throws OperationFailedException {
        final ModelNode encryptOp = createEmptyOperation("add-alias",
                PathAddress.pathAddress("subsystem", "elytron").append("credential-store", storeName));
        encryptOp.get("alias").set(alias);
        encryptOp.get("secret-value").set(keystorePassword);
        encryptOp.get(ModelDescriptionConstants.OPERATION_HEADERS).get("allow-resource-service-restart").set(true);
        return this.execute(encryptOp, "Encrypt password");
    }

    @Override
    public List<Path> getTemporaryPaths() {
        final Path standaloneDir = path.resolve("standalone");
        return List.of(standaloneDir.resolve("configuration").resolve("standalone_xml_history"),
                standaloneDir.resolve("data"),
                standaloneDir.resolve("log"),
                standaloneDir.resolve("tmp").resolve("vfs"));
    }
}
