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.caption.TranslatableCaption;
024import com.plotsquared.core.events.PlotFlagRemoveEvent;
025import com.plotsquared.core.events.Result;
026import com.plotsquared.core.player.PlotPlayer;
027import com.plotsquared.core.plot.Plot;
028import com.plotsquared.core.plot.PlotArea;
029import com.plotsquared.core.plot.flag.PlotFlag;
030import com.plotsquared.core.plot.flag.implementations.PriceFlag;
031import com.plotsquared.core.util.EconHandler;
032import com.plotsquared.core.util.EventDispatcher;
033import com.plotsquared.core.util.task.RunnableVal2;
034import com.plotsquared.core.util.task.RunnableVal3;
035import net.kyori.adventure.text.minimessage.Template;
036import org.checkerframework.checker.nullness.qual.NonNull;
037
038import java.util.Set;
039import java.util.concurrent.CompletableFuture;
040
041@CommandDeclaration(command = "buy",
042        usage = "/plot buy",
043        permission = "plots.buy",
044        category = CommandCategory.CLAIMING,
045        requiredType = RequiredType.NONE)
046public class Buy extends Command {
047
048    private final EventDispatcher eventDispatcher;
049    private final EconHandler econHandler;
050
051    @Inject
052    public Buy(
053            final @NonNull EventDispatcher eventDispatcher,
054            final @NonNull EconHandler econHandler
055    ) {
056        super(MainCommand.getInstance(), true);
057        this.eventDispatcher = eventDispatcher;
058        this.econHandler = econHandler;
059    }
060
061    @Override
062    public CompletableFuture<Boolean> execute(
063            final PlotPlayer<?> player, String[] args,
064            RunnableVal3<Command, Runnable, Runnable> confirm,
065            final RunnableVal2<Command, CommandResult> whenDone
066    ) {
067
068        PlotArea area = player.getPlotAreaAbs();
069        check(area, TranslatableCaption.of("errors.not_in_plot_world"));
070        check(this.econHandler.isEnabled(area), TranslatableCaption.of("economy.econ_disabled"));
071        final Plot plot;
072        if (args.length != 0) {
073            if (args.length != 1) {
074                sendUsage(player);
075                return CompletableFuture.completedFuture(false);
076            }
077            plot = check(Plot.getPlotFromString(player, args[0], true), null);
078        } else {
079            plot = check(player.getCurrentPlot(), TranslatableCaption.of("errors.not_in_plot"));
080        }
081        checkTrue(plot.hasOwner(), TranslatableCaption.of("info.plot_unowned"));
082        checkTrue(!plot.isOwner(player.getUUID()), TranslatableCaption.of("economy.cannot_buy_own"));
083        Set<Plot> plots = plot.getConnectedPlots();
084        checkTrue(
085                player.getPlotCount() + plots.size() <= player.getAllowedPlots(),
086                TranslatableCaption.of("permission.cant_claim_more_plots"),
087                Template.of("amount", String.valueOf(player.getAllowedPlots()))
088        );
089        double price = plot.getFlag(PriceFlag.class);
090        if (price <= 0) {
091            throw new CommandException(TranslatableCaption.of("economy.not_for_sale"));
092        }
093        checkTrue(
094                this.econHandler.isSupported(),
095                TranslatableCaption.of("economy.vault_or_consumer_null")
096        );
097        checkTrue(
098                this.econHandler.getMoney(player) >= price,
099                TranslatableCaption.of("economy.cannot_afford_plot"),
100                Template.of("money", this.econHandler.format(price)),
101                Template.of("balance", this.econHandler.format(this.econHandler.getMoney(player)))
102        );
103        this.econHandler.withdrawMoney(player, price);
104        // Failure
105        // Success
106        confirm.run(this, () -> {
107            player.sendMessage(
108                    TranslatableCaption.of("economy.removed_balance"),
109                    Template.of("money", this.econHandler.format(price))
110            );
111
112            this.econHandler.depositMoney(PlotSquared.platform().playerManager().getOfflinePlayer(plot.getOwnerAbs()), price);
113
114            PlotPlayer<?> owner = PlotSquared.platform().playerManager().getPlayerIfExists(plot.getOwnerAbs());
115            if (owner != null) {
116                owner.sendMessage(
117                        TranslatableCaption.of("economy.plot_sold"),
118                        Template.of("plot", plot.getId().toString()),
119                        Template.of("player", player.getName()),
120                        Template.of("price", this.econHandler.format(price))
121                );
122            }
123            PlotFlag<?, ?> plotFlag = plot.getFlagContainer().getFlag(PriceFlag.class);
124            PlotFlagRemoveEvent event = this.eventDispatcher.callFlagRemove(plotFlag, plot);
125            if (event.getEventResult() != Result.DENY) {
126                plot.removeFlag(event.getFlag());
127            }
128            plot.setOwner(player.getUUID());
129            plot.getPlotModificationManager().setSign(player.getName());
130            player.sendMessage(
131                    TranslatableCaption.of("working.claimed"),
132                    Template.of("plot", plot.getId().toString())
133            );
134            whenDone.run(Buy.this, CommandResult.SUCCESS);
135        }, () -> {
136            this.econHandler.depositMoney(player, price);
137            whenDone.run(Buy.this, CommandResult.FAILURE);
138        });
139        return CompletableFuture.completedFuture(true);
140    }
141
142}