/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.invulnerability.commands;

import io.github.nucleuspowered.nucleus.modules.invulnerability.InvulnerabilityPermissions;
import io.github.nucleuspowered.nucleus.modules.invulnerability.services.InvulnerabilityService;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandContext;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandExecutor;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandResult;
import io.github.nucleuspowered.nucleus.core.scaffold.command.NucleusParameters;
import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.Command;
import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.EssentialsEquivalent;
import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection;
import org.spongepowered.api.command.exception.CommandException;
import org.spongepowered.api.command.parameter.Parameter;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;

@EssentialsEquivalent({"god", "godmode", "tgm"})
@Command(
        aliases = {"god", "invuln", "invulnerability"},
        basePermission = InvulnerabilityPermissions.BASE_GOD,
        commandDescriptionKey = "god",
        associatedPermissions = {
                InvulnerabilityPermissions.OTHERS_GOD,
                InvulnerabilityPermissions.GOD_PVP_OVERRIDE
        }
)
public class InvulnerabilityCommand implements ICommandExecutor {

    @Override
    public Parameter[] parameters(final INucleusServiceCollection serviceCollection) {
        return new Parameter[] {
                serviceCollection.commandElementSupplier()
                        .createOnlyOtherPlayerPermissionElement(InvulnerabilityPermissions.OTHERS_GOD),
                NucleusParameters.OPTIONAL_ONE_TRUE_FALSE
        };
    }

    @Override
    public ICommandResult execute(final ICommandContext context) throws CommandException {
        final ServerPlayer pl = context.getPlayerFromArgs();
        final InvulnerabilityService service = context.getServiceCollection().getServiceUnchecked(InvulnerabilityService.class);
        final boolean god = context.getOne(NucleusParameters.OPTIONAL_ONE_TRUE_FALSE).orElse(!service.isInvulnerable(pl.uniqueId()));

        try {
            service.setInvulnerable(pl.uniqueId(), god);
        } catch (final Exception e) {
            // TODO: Better
            e.printStackTrace();
            return context.failResult();
        }

        if (!context.is(pl)) {
            context.sendMessage(god ? "command.god.player.on" : "command.god.player.off", pl.name());
        }

        context.sendMessageTo(pl, god ? "command.god.on" : "command.god.off");
        return context.successResult();
    }
}
