/*
 *   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.velocitycore.inventory;

import com.velocitypowered.api.proxy.Player;
import de.steamwar.network.packets.client.AnvilAnswerPacket;
import de.steamwar.network.packets.server.AnvilInventoryPacket;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.velocitycore.network.NetworkSender;
import lombok.AllArgsConstructor;
import lombok.Builder;

import java.util.HashMap;
import java.util.function.Consumer;

@AllArgsConstructor
@Builder(toBuilder = true)
public class SWAnvilInv {
    private static final HashMap<Integer, SWAnvilInv> openInv = new HashMap<>();

    public static void handleClick(AnvilAnswerPacket packet) {
        try {
            switch (packet.getAction()) {
                case LEFT_CLICK:
                    openInv.get(packet.getPlayerId()).leftClickCallback.run();
                    break;
                case CLOSE:
                    openInv.remove(packet.getPlayerId()).closeCallback.run();
                    break;
                case ANSWER:
                    openInv.get(packet.getPlayerId()).callback.accept(packet.getText());
                    break;
            }
        } catch (NullPointerException ignored) { }
    }

    private final Player player;
    private final String title;
    private final String defaultText;
    private final String material;

    private final Consumer<String> callback;
    private final Runnable closeCallback;
    private final Runnable leftClickCallback;

    public void open() {
        SteamwarUser user = SteamwarUser.get(player.getUniqueId());

        openInv.put(user.getId(), this);
        NetworkSender.send(player, new AnvilInventoryPacket(user.getId(), title, defaultText, material));
    }
}
