/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2023  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.bausystem.features.simulator.gui.base;

import de.steamwar.bausystem.BauSystem;
import de.steamwar.inventory.SWAnvilInv;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;

public class SimulatorAnvilGui<T extends Number> {

    private SWAnvilInv anvilInv;

    public SimulatorAnvilGui(Player player, String title, String defaultText, Function<String, T> mapper, Function<T, Boolean> value, SimulatorBaseGui back) {
        if (defaultText == null) {
            anvilInv = new SWAnvilInv(player, title);
        } else {
            anvilInv = new SWAnvilInv(player, title + ": " + defaultText);
        }
        AtomicBoolean error = new AtomicBoolean();
        anvilInv.addCloseCallback(() -> {
            Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
                if (error.get()) {
                    anvilInv.open();
                } else {
                    back.open();
                }
                error.set(false);
            }, 0);
        });
        anvilInv.setCallback(s -> {
            T t;
            try {
                t = mapper.apply(s);
            } catch (NumberFormatException e) {
                error.set(true);
                return;
            }
            try {
                if (!value.apply(t)) {
                    error.set(true);
                }
            } catch (Exception e) {
                // Ignore
            }
        });
    }

    public SimulatorAnvilGui<T> setItem(Material material) {
        anvilInv.setItem(material);
        return this;
    }

    public void open() {
        anvilInv.open();
    }
}
