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

import de.steamwar.lobby.portal.Portal;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

public class Portals extends BasicListener {

    private static final Map<Player, Deque<Portal>> portalStack = new HashMap<>();

    public static Deque<Portal> getStack(Player player) {
        return portalStack.get(player);
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent e) {
        portalStack.put(e.getPlayer(), new ArrayDeque<>());
    }

    @EventHandler
    public void onMove(PlayerMoveEvent e) {
        Location from = e.getFrom();
        Location to = e.getTo();
        assert to != null;

        Portal portal = Portal.getPortal(from, to);
        if (portal == null)
            return;

        Player player = e.getPlayer();
        Deque<Portal> lastPortals = portalStack.get(player);
        if(!lastPortals.isEmpty() && lastPortals.peek() == portal)
            return;

        portal.handle(player, from, to);
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent e) {
        portalStack.remove(e.getPlayer());
    }
}
