/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.schematicsystem;

import de.steamwar.sql.SchematicNode;
import de.steamwar.sql.SteamwarUser;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.bukkit.entity.Player;

public class SafeSchematicNode {

    public static Result setParent(@NonNull SteamwarUser user, @NonNull SchematicNode node, SchematicNode newParent) {
        if(user.getId() != node.getOwner()) {
            return Result.NOT_OWNER;
        }
        if(newParent == null) {
            if(SchematicNode.list(user, null)
                    .stream().map(SchematicNode::getName).anyMatch(s -> s.equalsIgnoreCase(node.getName()))) {
                return Result.ALREADY_IN_DIRECTORY;
            }

            node.setParent(null);
        } else {
            if(!newParent.isDir()) {
                return Result.NOT_A_DIR;
            }

            if(SchematicNode.list(user, newParent.getId())
                    .stream().map(SchematicNode::getName).anyMatch(s -> s.equalsIgnoreCase(node.getName()))) {
                return Result.ALREADY_IN_DIRECTORY;
            }

            node.setParent(newParent.getId());
        }
        return Result.DONE;
    }

    public static Result setName(@NonNull SteamwarUser user, @NonNull SchematicNode node, @NonNull String name) {
        if(user.getId() != node.getOwner()) {
            return Result.NOT_OWNER;
        }

        if(SchematicNode.invalidSchemName(new String[]{name})) {
            return Result.INVALID_NAME;
        }

        if(SchematicNode.list(user, node.getParent()).stream().map(SchematicNode::getName).anyMatch(s -> s.equalsIgnoreCase(name))) {
            return Result.ALREADY_IN_DIRECTORY;
        }

        node.setName(name);
        return Result.DONE;
    }

    @AllArgsConstructor
    public enum Result {
        DONE,
        NOT_A_DIR,
        ALREADY_IN_DIRECTORY,
        INVALID_NAME,
        NOT_OWNER;

        public void sendError(Player player) {
            SchematicSystem.MESSAGE.send("SAFE_NODE_" + this.name(), player);
        }

        public boolean isSuccessful() {
            return this == DONE;
        }
    }
}
