/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.misslewars.scripts.implemented;

import com.google.gson.JsonObject;
import de.steamwar.misslewars.MissileWars;
import de.steamwar.misslewars.scripts.RunnableScript;
import de.steamwar.misslewars.scripts.RunnableScriptEvent;
import org.bukkit.Location;

import java.util.HashMap;
import java.util.Map;

import static de.steamwar.misslewars.scripts.utils.JsonUtils.getBoolean;
import static de.steamwar.misslewars.scripts.utils.JsonUtils.getString;

public class FilterScript implements RunnableScript {

    private static final Map<String, ScriptFunction> filterMap = new HashMap<>();

    static {
        filterMap.put("nearportal", (runnableScriptEvent, doubles) -> {
            Location location = runnableScriptEvent.getLocation();
            int bz = MissileWars.getBlueTeam().getPortalZ();
            int rz = MissileWars.getRedTeam().getPortalZ();
            int offset = (int) Math.signum(bz - rz) * 5;

            int blockZ = location.getBlockZ();
            if (offset > 0) return (blockZ > bz - offset) || (blockZ < rz + offset);
            else return (blockZ < bz - offset) || (blockZ > rz + offset);
        });
        filterMap.put("nearspawn", (runnableScriptEvent, doubles) -> {
            Location location = runnableScriptEvent.getLocation();
            return MissileWars.getBlueTeam().getSpawn().distance(location) < 3 || MissileWars.getRedTeam().getSpawn().distance(location) < 3;
        });
    }

    private boolean inverted;
    private ScriptFunction filter;

    public FilterScript(JsonObject filter) {
        this.filter = filterMap.getOrDefault(getString(filter, "filter", "").toLowerCase(), null);
        inverted = getBoolean(filter, "invert", false);
    }

    @Override
    public boolean execute(RunnableScriptEvent runnableScriptEvent) {
        return defaultExecution(filter, true, b -> b ^ inverted, runnableScriptEvent);
    }

}
