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

import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
import org.jboss.installer.postinstall.TaskPrinter;
import org.jboss.installer.postinstall.ldap.SecurityDomain;
import org.jboss.installer.postinstall.server.EmbeddedServer;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.jboss.as.controller.operations.common.Util.createEmptyOperation;
import static org.jboss.installer.postinstall.task.SecurityDomainTask.REALM_SUFFIX;

public class PropertiesSecurity {

    private final TaskPrinter printer;

    public PropertiesSecurity(TaskPrinter printer) {
        this.printer = printer;
    }

    public List<ModelNode> toOperations(EmbeddedServer server, String domainName, PropertiesFileConfig propertiesFileConfig) throws IOException {
        final ArrayList<ModelNode> ops = new ArrayList<>();

        final boolean plainText = propertiesFileConfig.isPlainText();
        final String hashEncoding = propertiesFileConfig.getHashEncoding();
        final String hashCharset = propertiesFileConfig.getHashCharset();

        initPropertyFiles(domainName, propertiesFileConfig.getGroupsFilePath(), propertiesFileConfig.getUsersFilePath(), plainText);
        // add realm
        final ModelNode addRealmOp = addPropertyFileRealmOp(server, domainName, propertiesFileConfig.getGroupsFilePath(),
                propertiesFileConfig.getUsersFilePath(), plainText, hashEncoding, hashCharset);

        ops.add(addRealmOp);

        // add domain with the new realm
        final ModelNode addDomainOp = new SecurityDomain().createSecurityDomain(new SecurityDomain.Model(domainName, domainName + REALM_SUFFIX, true));

        ops.add(addDomainOp);

        // In the future, we should add http-authentication-factory and application-security-domain
        return ops;
    }

    private ModelNode addPropertyFileRealmOp(EmbeddedServer server, String domainName, Path groupFileName, Path usersFileName, boolean plainText, String hashEncoding, String hashCharset) {
        final ModelNode addRealmOp = createEmptyOperation("add", PathAddress.pathAddress("subsystem", "elytron")
                .append("properties-realm", domainName + REALM_SUFFIX));
        addRealmOp.get("groups-attribute").set("group");
        final ModelNode groupsNode = server.relativise(groupFileName, new ModelNode());
        addRealmOp.get("groups-properties").set(groupsNode);

        final ModelNode usersNode = server.relativise(usersFileName, new ModelNode());
        usersNode.get("plain-text").set(plainText);
        addRealmOp.get("users-properties").set(usersNode);

        if (!plainText) {
            addRealmOp.get("hash-encoding").set(hashEncoding);
            addRealmOp.get("hash-charset").set(hashCharset);
        }

        return addRealmOp;
    }

    private void initPropertyFiles(String domainName, Path groupsFilePath, Path usersFilePath, boolean plainText) throws IOException {
        if (!Files.exists(usersFilePath)) {
            createFile(usersFilePath);
            if (!plainText) {
                // TODO: should add that as well if already existing, otherwise it won't work
                writeFile(domainName, usersFilePath);
            }
        }
        if (!Files.exists(groupsFilePath)) {
            createFile(groupsFilePath);
        }
    }

    private void writeFile(String domainName, Path filePath) throws IOException {
        try {
            Files.write(filePath, ("#$REALM_NAME=" + domainName + "-realm$").getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE);
        } catch (IOException e) {
            printer.print("tasks.sec_dom.file_write_error", filePath.toString());
            throw e;
        }
    }

    private Path createFile(Path filePath) throws IOException {
        try {
            return Files.createFile(filePath);
        } catch (IOException e) {
            printer.print("tasks.sec_dom.file_create_error", filePath.toString());
            throw e;
        }
    }

    public static class PropertiesFileConfig {
        // serialization keys
        private static final String USERS_FILE_PATH = "standaloneUsersFilePath";
        private static final String GROUPS_FILE_PATH = "standaloneGroupsFilePath";
        private static final String PLAIN_TEXT = "plainText";
        private static final String HASH_ENCODING = "hashEncoding";
        private static final String HASH_CHARSET = "hashCharset";
        // end of serialization keys
        private Path usersFilePath;
        private Path groupsFilePath;
        private boolean plainText;
        private String hashEncoding;
        private String hashCharset;

        public PropertiesFileConfig() {

        }

        public PropertiesFileConfig(Map<String, String> attributes) {
            usersFilePath = Paths.get(attributes.get(USERS_FILE_PATH));
            groupsFilePath = Paths.get(attributes.get(GROUPS_FILE_PATH));

            plainText = Boolean.parseBoolean(attributes.get(PLAIN_TEXT));
            hashEncoding = attributes.get(HASH_ENCODING);
            hashCharset = attributes.get(HASH_CHARSET);
        }

        public Map<String, String> toAttributes() {
            final HashMap<String, String> attrs = new HashMap<>();
            attrs.put(USERS_FILE_PATH, usersFilePath.toString());
            attrs.put(GROUPS_FILE_PATH, groupsFilePath.toString());
            attrs.put(PLAIN_TEXT, plainText + "");
            attrs.put(HASH_ENCODING, hashEncoding);
            attrs.put(HASH_CHARSET, hashCharset);
            return attrs;
        }

        public Path getUsersFilePath() {
            return usersFilePath;
        }

        public void setUsersFilePath(Path standaloneUsersFilePath) {
            this.usersFilePath = standaloneUsersFilePath;
        }
        public Path getGroupsFilePath() {
            return groupsFilePath;
        }

        public void setGroupsFilePath(Path standaloneGroupsFilePath) {
            this.groupsFilePath = standaloneGroupsFilePath;
        }

        public boolean isPlainText() {
            return plainText;
        }

        public void setPlainText(boolean plainText) {
            this.plainText = plainText;
        }

        public String getHashEncoding() {
            return hashEncoding;
        }

        public void setHashEncoding(String hashEncoding) {
            this.hashEncoding = hashEncoding;
        }

        public String getHashCharset() {
            return hashCharset;
        }

        public void setHashCharset(String hashCharset) {
            this.hashCharset = hashCharset;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            PropertiesFileConfig that = (PropertiesFileConfig) o;
            return plainText == that.plainText && Objects.equals(usersFilePath, that.usersFilePath) && Objects.equals(groupsFilePath, that.groupsFilePath) && Objects.equals(hashEncoding, that.hashEncoding) && Objects.equals(hashCharset, that.hashCharset);
        }

        @Override
        public int hashCode() {
            return Objects.hash(usersFilePath, groupsFilePath, plainText, hashEncoding, hashCharset);
        }
    }
}
