/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package works.chatterbox.hooks.factions.stages;

import com.google.common.base.Preconditions;
import com.massivecraft.factions.FPlayer;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import works.chatterbox.chatterbox.channels.ConfigChannel;
import works.chatterbox.chatterbox.messages.Message;
import works.chatterbox.chatterbox.pipeline.PipelineContext;
import works.chatterbox.chatterbox.pipeline.stages.Stage;
import works.chatterbox.hooks.factions.FactionsHook;
import works.chatterbox.hooks.factions.FactionsMagic;

import java.util.Set;
import java.util.stream.Collectors;

public class FactionRecipientStage implements Stage {

    private FactionsHook factionsHook;

    public FactionRecipientStage(@NotNull final FactionsHook factionsHook) {
        Preconditions.checkNotNull(factionsHook, "factionsHook was null");
        this.factionsHook = factionsHook;
    }

    @Override
    public void process(@NotNull final Message message, @NotNull final PipelineContext context) {
        final FactionsMagic fm = this.factionsHook.getFactionsMagic();
        if (message.isCancelled() || fm == null) return;
        if (!(message.getChannel() instanceof ConfigChannel)) return;
        final ConfigChannel channel = (ConfigChannel) message.getChannel();
        final boolean self = channel.getNode().getNode("factions").getNode("self").getBoolean(false);
        if (!self) return; // TODO: All, relationships
        final Player player = message.getSender().getPlayer();
        if (player == null) return;
        final FPlayer fp = fm.getFPlayers().getByPlayer(player);
        // Get the Faction ID
        final String factionID = fp.getFaction().getId();
        // Get a list of recipients that also have that Faction ID
        final Set<Player> keep = message.getRecipients().stream()
            .filter(member -> factionID.equals(fm.getFPlayers().getByPlayer(member).getFaction().getId()))
            .collect(Collectors.toSet());
        // Retain that list
        message.getRecipients().retainAll(keep);
    }
}
