/*
 * This file is a part of the SteamWar software.
 *
 * Copyright (C) 2022  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.network.handlers;

import com.google.gson.JsonParser;
import de.steamwar.inventory.SWInventory;
import de.steamwar.inventory.SWItem;
import de.steamwar.network.NetworkSender;
import de.steamwar.network.packets.PacketHandler;
import de.steamwar.network.packets.client.InventoryCallbackPacket;
import de.steamwar.network.packets.server.InventoryPacket;
import de.steamwar.sql.SteamwarUser;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;

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

public class InventoryHandler extends PacketHandler {

    @Handler
    public static void handleInventoryPacket(InventoryPacket packet) {
        Player player = Bukkit.getPlayer(SteamwarUser.get(packet.getPlayer()).getUUID());
        Map<Integer, SWItem> items = new HashMap<>();
        packet.getItems().forEach((i, item) -> {
            @SuppressWarnings("deprecation") SWItem it = SWItem.getItemFromJson(new JsonParser().parse(item).getAsJsonObject());
            it.setCallback(click -> NetworkSender.send(InventoryCallbackPacket.builder().owner(packet.getPlayer()).position(i).type(InventoryCallbackPacket.CallbackType.CLICK).clickType(InventoryCallbackPacket.ClickType.getByName(click.name())).build(), player));
            items.put(i, it);
        });

        SWInventory inventory = new SWInventory(player, packet.getSize(), packet.getTitle(), items);
        inventory.addCloseCallback(click -> {
            if(player.getOpenInventory().getType() != InventoryType.CHEST)
                NetworkSender.send(InventoryCallbackPacket.builder().owner(packet.getPlayer()).type(InventoryCallbackPacket.CallbackType.CLOSE).build(), player);
        });
        inventory.open();
    }
}
