/*
 *   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.commands.schematiccommand.parts;

import de.steamwar.command.AbstractSWCommand;
import de.steamwar.command.SWCommand;
import de.steamwar.linkage.Linked;
import de.steamwar.schematicsystem.SchematicSystem;
import de.steamwar.schematicsystem.commands.schematiccommand.SchematicCommand;
import de.steamwar.sql.*;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static de.steamwar.schematicsystem.commands.schematiccommand.SchematicCommandUtils.getUser;
import static de.steamwar.schematicsystem.commands.schematiccommand.SchematicCommandUtils.mkdirs;

@AbstractSWCommand.PartOf(SchematicCommand.class)
@Linked
public class MemberPart extends SWCommand {
    public MemberPart() {
        super(null);
    }

    @Register("addmember")
    public void addMember(Player player, @Validator("isOwnerValidator") SchematicNode node, SteamwarUser... targets) {
        SteamwarUser user = getUser(player);
        if (Punishment.isPunished(user, Punishment.PunishmentType.NoSchemSharing, punishment -> SchematicSystem.MESSAGE.send("COMMAND_ADD_PUNISH", player, punishment.getReason()))) {
            return;
        }
        List<SteamwarUser> added = new ArrayList<>();
        for (SteamwarUser target : targets) {
            if (Punishment.isPunished(target,
                    Punishment.PunishmentType.NoSchemReceiving,
                    punishment -> SchematicSystem.MESSAGE.send("COMMAND_ADD_USER_PUNISHED", player, target.getUserName()))) {
                continue;
            }

            if (user.getId() == target.getId()) {
                SchematicSystem.MESSAGE.send("COMMAND_ADD_OWN", player);
                continue;
            }

            if (target.getId() == 0) {
                SchematicSystem.MESSAGE.send("COMMAND_ADD_PUBLIC", player);
                continue;
            }

            if (NodeMember.getNodeMember(node.getId(), target.getId()) != null) {
                SchematicSystem.MESSAGE.send("COMMAND_ADD_ALREADY", player, target.getUserName());
                continue;
            }

            NodeMember.createNodeMember(node.getId(), target.getId());
            added.add(target);

            Player t = Bukkit.getPlayer(target.getUUID());
            if (t != null) {
                SchematicSystem.MESSAGE.send("COMMAND_ADD_ADDED", t, node.generateBreadcrumbs(user), player.getName());
            }
        }

        Optional<String> reduced = added.stream().map(SteamwarUser::getUserName).reduce((s, s2) -> s + ", " + s2);
        if (reduced.isPresent()) {
            SchematicSystem.MESSAGE.send(added.size() > 1 ? "COMMAND_ADD_MANY" : "COMMAND_ADD_ONE", player, reduced.get());
        } else {
            SchematicSystem.MESSAGE.send("COMMAND_ADD_NONE", player);
        }
    }

    @Register("delmember")
    public void delMember(Player player, @Validator("isOwnerValidator") SchematicNode node, @Mapper("memberMapper") NodeMember member) {
        SteamwarUser user = getUser(player);
        SteamwarUser target = SteamwarUser.byId(member.getMember());

        List<SchematicNode> nodes = SchematicNode.deepGet(node.getId(), node1 -> node1.getOwner() != user.getId());
        if (!nodes.isEmpty()) {
            for (SchematicNode schematicNode : nodes) {
                SchematicNode newNode = mkdirs(schematicNode.generateBreadcrumbs(user).split("/"), target, 1);
                if (SchematicNode.getSchematicNode(schematicNode.getName(), newNode == null ? 0 : newNode.getId()) != null) {
                    schematicNode.setName(schematicNode.getName() + "-" + Instant.now().getEpochSecond() % 1000);
                }
                schematicNode.setParent(newNode == null ? null : newNode.getId());
            }
        }

        member.delete();
        SchematicSystem.MESSAGE.send("COMMAND_DELMEM_DONE", player, target.getUserName(), node.generateBreadcrumbs(user));

        Player t = Bukkit.getPlayer(target.getUUID());
        if (t != null) {
            SchematicSystem.MESSAGE.send("COMMAND_DELMEM_DELETED", t, node.getName(), player.getName());
        }
    }

    @Register("addteam")
    public void addTeam(Player player, @Validator("isOwnerValidator") SchematicNode node) {
        SteamwarUser user = getUser(player);
        Team team = Team.byId(user.getTeam());
        if (team == null || team.getTeamId() == 0) {
            SchematicSystem.MESSAGE.send("COMMAND_ADD_TEAM_NOT_IN_TEAM", player);
            return;
        }

        addMember(player, node, team.getMembers().stream().map(SteamwarUser::byId).filter(steamwarUser -> steamwarUser.getId() != user.getId()).toArray(SteamwarUser[]::new));
    }

    @Register("delteam")
    public void remTeam(Player player, @Validator("isOwnerValidator") SchematicNode node) {
        SteamwarUser user = getUser(player);
        Team team = Team.byId(user.getTeam());
        if (team == null || team.getTeamId() == 0) {
            SchematicSystem.MESSAGE.send("COMMAND_DEL_TEAM_NOT_IN_TEAM", player);
            return;
        }

        List<String> removed = new ArrayList<>();
        for (Integer member : team.getMembers()) {
            if (user.getId() == member) continue;
            NodeMember nodeMember = NodeMember.getNodeMember(node.getId(), member);
            if (nodeMember != null) {
                nodeMember.delete();
                removed.add(SteamwarUser.byId(member).getUserName());
            }
        }

        Optional<String> reduced = removed.stream().reduce((s, s2) -> s + ", " + s2);
        if (reduced.isPresent()) {
            SchematicSystem.MESSAGE.send("COMMAND_DEL_TEAM_DONE", player, reduced.get());
        } else {
            SchematicSystem.MESSAGE.send("COMMAND_DEL_TEAM_NONE", player);
        }
    }

    @Register("clearmember")
    public void clearMember(Player player, @Validator("isOwnerValidator") SchematicNode node) {
        node.getMembers().forEach(NodeMember::delete);
        SchematicSystem.MESSAGE.send("COMMAND_CLEAR_MEMBER_DONE", player);
    }

    @Register("delallmember")
    public void delAllMember(Player player, SteamwarUser target) {
        SteamwarUser user = getUser(player);
        int i = 0;
        for (NodeMember nodeMember : NodeMember.getSchematics(target.getId())) {
            SchematicNode node = SchematicNode.getSchematicNode(nodeMember.getNode());
            if (node.getOwner() == user.getId()) {
                nodeMember.delete();
                i++;
            }
        }
        SchematicSystem.MESSAGE.send("COMMAND_DEL_ALL_MEMBER", player, target.getUserName(), i);
    }
}
