/*
 *   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 de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter;

import java.util.List;
import java.util.function.Function;

public class SWStreamInv<T> extends SWInventory {
    private final SWListInv.ListCallback<T> callback;
    private final Function<Integer, List<SWListInv.SWListEntry<T>>> constructor;
    private int page;

    public SWStreamInv(PlayerChatter chatter, Message title, SWListInv.ListCallback<T> callback, Function<Integer, List<SWListInv.SWListEntry<T>>> constructor) {
        super(chatter, 54, title);
        this.callback = callback;
        this.constructor = constructor;
        page = 0;
    }

    @Override
    public void open() {
        List<SWListInv.SWListEntry<T>> entries = constructor.apply(page);

        if (page != 0) {
            addItem(45, new SWItem("LIME_DYE", new Message("INV_PAGE_BACK", "e")), (InvCallback.ClickType click) -> {
                page--;
                open();
            });
        } else {
            addItem(45, new SWItem("GRAY_DYE", new Message("INV_PAGE_BACK", "7")), (InvCallback.ClickType click) -> {
            });
        }

        if (entries.size() == 45) {
            addItem(53, new SWItem("LIME_DYE", new Message("INV_PAGE_NEXT", "e")), (InvCallback.ClickType click) -> {
                page++;
                open();
            });
        } else {
            addItem(53, new SWItem("GRAY_DYE", new Message("INV_PAGE_NEXT", "7")), (InvCallback.ClickType click) -> {
            });
        }

        for (int i = 0; i < entries.size(); i++) {
            SWListInv.SWListEntry<T> item = entries.get(i);
            addItem(i, item.getItem());
            setCallback(i, (InvCallback.ClickType click) -> {
                close();
                callback.clicked(click, item.getObject());
            });
        }

        super.open();
    }
}
