001/*
002 * PlotSquared, a land and world management plugin for Minecraft.
003 * Copyright (C) IntellectualSites <https://intellectualsites.com>
004 * Copyright (C) IntellectualSites team and contributors
005 *
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
018 */
019package com.plotsquared.core.command;
020
021import com.google.inject.Inject;
022import com.plotsquared.core.PlotSquared;
023import com.plotsquared.core.configuration.Settings;
024import com.plotsquared.core.configuration.caption.TranslatableCaption;
025import com.plotsquared.core.events.PlayerBuyPlotEvent;
026import com.plotsquared.core.events.Result;
027import com.plotsquared.core.player.OfflinePlotPlayer;
028import com.plotsquared.core.player.PlotPlayer;
029import com.plotsquared.core.plot.Plot;
030import com.plotsquared.core.plot.PlotArea;
031import com.plotsquared.core.plot.flag.PlotFlag;
032import com.plotsquared.core.plot.flag.implementations.PriceFlag;
033import com.plotsquared.core.util.EconHandler;
034import com.plotsquared.core.util.EventDispatcher;
035import com.plotsquared.core.util.task.RunnableVal2;
036import com.plotsquared.core.util.task.RunnableVal3;
037import net.kyori.adventure.text.Component;
038import net.kyori.adventure.text.minimessage.tag.Tag;
039import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
040import org.checkerframework.checker.nullness.qual.NonNull;
041
042import java.util.Set;
043import java.util.concurrent.CompletableFuture;
044
045@CommandDeclaration(command = "buy",
046        usage = "/plot buy",
047        permission = "plots.buy",
048        category = CommandCategory.CLAIMING,
049        requiredType = RequiredType.NONE)
050public class Buy extends Command {
051
052    private final EventDispatcher eventDispatcher;
053    private final EconHandler econHandler;
054
055    @Inject
056    public Buy(
057            final @NonNull EventDispatcher eventDispatcher,
058            final @NonNull EconHandler econHandler
059    ) {
060        super(MainCommand.getInstance(), true);
061        this.eventDispatcher = eventDispatcher;
062        this.econHandler = econHandler;
063    }
064
065    @Override
066    public CompletableFuture<Boolean> execute(
067            final PlotPlayer<?> player, String[] args,
068            RunnableVal3<Command, Runnable, Runnable> confirm,
069            final RunnableVal2<Command, CommandResult> whenDone
070    ) {
071
072        PlotArea area = player.getPlotAreaAbs();
073        check(area, TranslatableCaption.of("errors.not_in_plot_world"));
074        check(this.econHandler.isEnabled(area), TranslatableCaption.of("economy.econ_disabled"));
075        final Plot plot;
076        if (args.length != 0) {
077            if (args.length != 1) {
078                sendUsage(player);
079                return CompletableFuture.completedFuture(false);
080            }
081            plot = check(Plot.getPlotFromString(player, args[0], true), null);
082        } else {
083            plot = check(player.getCurrentPlot(), TranslatableCaption.of("errors.not_in_plot"));
084        }
085        checkTrue(plot.hasOwner(), TranslatableCaption.of("info.plot_unowned"));
086        checkTrue(!plot.isOwner(player.getUUID()), TranslatableCaption.of("economy.cannot_buy_own"));
087        Set<Plot> plots = plot.getConnectedPlots();
088        int plotCount = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(plot.getWorldName());
089        checkTrue(
090                plotCount + plots.size() <= player.getAllowedPlots(),
091                TranslatableCaption.of("permission.cant_claim_more_plots"),
092                TagResolver.resolver("amount", Tag.inserting(Component.text(player.getAllowedPlots())))
093        );
094        double priceFlag = plot.getFlag(PriceFlag.class);
095        if (priceFlag <= 0) {
096            throw new CommandException(TranslatableCaption.of("economy.not_for_sale"));
097        }
098        checkTrue(
099                this.econHandler.isSupported(),
100                TranslatableCaption.of("economy.vault_or_consumer_null")
101        );
102
103        PlayerBuyPlotEvent event = this.eventDispatcher.callPlayerBuyPlot(player, plot, priceFlag);
104        if (event.getEventResult() == Result.DENY) {
105            throw new CommandException(TranslatableCaption.of("economy.cannot_buy_blocked"));
106        }
107
108        double price = event.getEventResult() == Result.FORCE ? 0 : event.price();
109        if (this.econHandler.getMoney(player) < price) {
110            throw new CommandException(
111                    TranslatableCaption.of("economy.cannot_afford_plot"),
112                    TagResolver.builder()
113                            .tag("money", Tag.inserting(Component.text(this.econHandler.format(price))))
114                            .tag("balance", Tag.inserting(Component.text(this.econHandler.format(this.econHandler.getMoney(player)))))
115                            .build()
116            );
117        }
118        this.econHandler.withdrawMoney(player, price);
119        // Failure
120        // Success
121        confirm.run(this, () -> {
122            player.sendMessage(
123                    TranslatableCaption.of("economy.removed_balance"),
124                    TagResolver.resolver("money", Tag.inserting(Component.text(this.econHandler.format(price))))
125            );
126
127            OfflinePlotPlayer previousOwner = PlotSquared.platform().playerManager().getOfflinePlayer(plot.getOwnerAbs());
128            this.econHandler.depositMoney(previousOwner, price);
129
130            PlotPlayer<?> owner = PlotSquared.platform().playerManager().getPlayerIfExists(plot.getOwnerAbs());
131            if (owner != null) {
132                owner.sendMessage(
133                        TranslatableCaption.of("economy.plot_sold"),
134                        TagResolver.builder()
135                                .tag("plot", Tag.inserting(Component.text(plot.getId().toString())))
136                                .tag("player", Tag.inserting(Component.text(player.getName())))
137                                .tag("price", Tag.inserting(Component.text(this.econHandler.format(price))))
138                                .build()
139                );
140            }
141            PlotFlag<?, ?> plotFlag = plot.getFlagContainer().getFlag(PriceFlag.class);
142            if (this.eventDispatcher.callFlagRemove(plotFlag, plot).getEventResult() != Result.DENY) {
143                plot.removeFlag(plotFlag);
144            }
145            plot.setOwner(player.getUUID());
146            plot.getPlotModificationManager().setSign(player.getName());
147            player.sendMessage(
148                    TranslatableCaption.of("working.claimed"),
149                    TagResolver.resolver("world", Tag.inserting(Component.text(plot.getArea().getWorldName()))),
150                    TagResolver.resolver("plot", Tag.inserting(Component.text(plot.getId().toString())))
151            );
152            this.eventDispatcher.callPostPlayerBuyPlot(player, previousOwner, plot, price);
153            whenDone.run(Buy.this, CommandResult.SUCCESS);
154        }, () -> {
155            this.econHandler.depositMoney(player, price);
156            whenDone.run(Buy.this, CommandResult.FAILURE);
157        });
158        return CompletableFuture.completedFuture(true);
159    }
160
161}