/*
 *   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.network.handlers;

import com.velocitypowered.api.proxy.Player;
import de.steamwar.linkage.Linked;
import de.steamwar.velocitycore.inventory.InvCallback;
import de.steamwar.velocitycore.inventory.SWInventory;
import de.steamwar.velocitycore.network.NetworkSender;
import de.steamwar.velocitycore.network.ServerMetaInfo;
import de.steamwar.messages.Chatter;
import de.steamwar.network.packets.PacketHandler;
import de.steamwar.network.packets.client.InventoryCallbackPacket;
import de.steamwar.network.packets.server.CloseInventoryPacket;
import de.steamwar.sql.SteamwarUser;

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

@Linked
public class InventoryCallbackHandler extends PacketHandler {

    public static final Map<Integer, SWInventory> inventoryHashMap = new HashMap<>();

    @Handler
    public void handle(InventoryCallbackPacket packet) {
        SteamwarUser owner = SteamwarUser.get(packet.getOwner());
        InventoryCallbackPacket.CallbackType type = packet.getType();
        if(!inventoryHashMap.containsKey(owner.getId())) {
            Chatter.of(owner).system("UPDATE_INTERRUPTION");
            if(type == InventoryCallbackPacket.CallbackType.CLICK) {
                NetworkSender.send((Player) ((ServerMetaInfo) packet.getMetaInfos()).sender(), new CloseInventoryPacket(owner.getId()));
            }
            return;
        }
        if(type == InventoryCallbackPacket.CallbackType.CLICK) {
            int pos = packet.getPosition();
            InvCallback.ClickType clickType = InvCallback.ClickType.valueOf(packet.getClickType().name());
            inventoryHashMap.get(owner.getId()).handleCallback(clickType, pos);
        }else if(type == InventoryCallbackPacket.CallbackType.CLOSE) {
            if(inventoryHashMap.get(owner.getId()).isNext()) {
                inventoryHashMap.get(owner.getId()).handleClose();
                return;
            }
            inventoryHashMap.get(owner.getId()).setNext(true);
        }
    }
}
