/*
 *   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 lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.util.List;

public class SWListInv<T> extends SWInventory {
    @Setter
    private ListCallback<T> callback;
    private final List<SWListEntry<T>> elements;
    private int page;

    public SWListInv(PlayerChatter p, Message t, List<SWListEntry<T>> l, ListCallback<T> c){
        super(p, (l.size()>45) ? 54 : (l.size() + 9-l.size()%9), t);
        callback = c;
        elements = l;
        page = 0;
    }

    @Override
    public void open(){
        if(elements.size() > 54){
            if(page != 0)
                addItem(45, new SWItem(new Message("INV_PAGE_BACK", "e"), 10), (InvCallback.ClickType click) -> {
                    page--;
                    open();
                });
            else
                addItem(45, new SWItem(new Message("INV_PAGE_BACK", "7"), 8), (InvCallback.ClickType click) -> {});
            if(page < elements.size()/45)
                addItem(53, new SWItem(new Message("INV_PAGE_NEXT", "e"), 10), (InvCallback.ClickType click) -> {
                    page++;
                    open();
                });
            else
                addItem(53, new SWItem(new Message("INV_PAGE_NEXT", "7"), 8), (InvCallback.ClickType click) -> {});
        }

        int ipageLimit = elements.size() - page*45;
        if(ipageLimit > 45 && elements.size() > 54){
            ipageLimit = 45;
        }
        int i = page*45;
        for(int ipage=0; ipage < ipageLimit; ipage++ ){
            SWItem e = elements.get(i).getItem();

            final int pos = i;
            addItem(ipage, e);
            setCallback(ipage, (InvCallback.ClickType click) -> callback.clicked(click, elements.get(pos).getObject()));
            i++;
        }
        super.open();
    }

    public interface ListCallback<T>{
        void clicked(InvCallback.ClickType click, T element);
    }

    @Getter
    @AllArgsConstructor
    public static class SWListEntry<T> {
        final SWItem item;
        final T object;
    }
}
