package com.shanebeestudios.skbee.elements.scoreboard.expressions;

import ch.njol.skript.classes.Changer.ChangeMode;
import ch.njol.skript.expressions.base.SimplePropertyExpression;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.Kleenean;
import ch.njol.util.coll.CollectionUtils;
import com.github.shanebeee.skr.Registration;
import org.bukkit.event.Event;
import org.bukkit.scoreboard.Team;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

@SuppressWarnings("deprecation")
public class ExprTeamName extends SimplePropertyExpression<Team, String> {

    public static void register(Registration reg) {
        reg.newPropertyExpression(ExprTeamName.class, String.class, "team [:display] name", "teams")
            .name("Team - Name")
            .description("Represents the name and display name of a team.",
                "\nNOTE: Display name can be set, name cannot be set.")
            .examples("set team display name of {_team} to \"The Warriors\"",
                "set team display name of team of player to \"The Rednecks\"",
                "set team display name of team named \"blue-team\" to \"Blue Team\"",
                "set {_name} to team name of team of player")
            .since("2.10.0")
            .register();
    }

    private boolean display;

    @SuppressWarnings("NullableProblems")
    @Override
    public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
        this.display = parseResult.hasTag("display");
        return super.init(exprs, matchedPattern, isDelayed, parseResult);
    }

    @Override
    public @Nullable String convert(Team team) {
        return this.display ? team.getDisplayName() : team.getName();
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public @Nullable Class<?>[] acceptChange(ChangeMode mode) {
        if (this.display && mode == ChangeMode.SET) return CollectionUtils.array(String.class);
        return null;
    }

    @SuppressWarnings({"NullableProblems", "ConstantValue"})
    @Override
    public void change(Event event, @Nullable Object[] delta, ChangeMode mode) {
        if (!this.display) return;
        if (delta != null && delta[0] instanceof String name) {
            for (Team team : getExpr().getArray(event)) {
                team.setDisplayName(name);
            }
        }
    }

    @Override
    public @NotNull Class<? extends String> getReturnType() {
        return String.class;
    }

    @Override
    protected @NotNull String getPropertyName() {
        return this.display ? "team display name" : "team name";
    }

}
