package com.yaohun.storyline.listener;

import com.yaohun.storyline.Storyline;
import com.yaohun.storyline.core.Quest;
import com.yaohun.storyline.data.PlayerData;
import com.yaohun.storyline.manage.PlayerManager;
import com.yaohun.storyline.manage.QuestManager;
import com.yaohun.storyline.util.MessageUtil;
import me.Demon.DemonWarps.WarpAPI;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.scheduler.BukkitRunnable;

public class PlayerListener implements Listener {

    @EventHandler
    public void onChange(PlayerChangedWorldEvent e) {
        Player player = e.getPlayer();
        if(player.getLevel() >= 16){
            return;
        }
        String playerName = player.getName();
        PlayerManager manager = Storyline.getPlayerManager();
        PlayerData playerData = manager.getPlayerData(playerName);

        if (playerData == null) return;

        // 玩家若已完成所有任务则直接返回
        if(playerData.isAllCompleted()){
            return;
        }

        Quest quest = QuestManager.getQuest(playerData.getCurrentQuest());
        if (quest == null) return;
        Location questStart = quest.getStartingPoint();
        // 判断是否进入与任务起点不同的世界
        if (!player.getWorld().getName().equals(questStart.getWorld().getName())) {
            new BukkitRunnable() {
                @Override
                public void run() {
                    // 传送回主线任务起点
                    player.teleport(questStart);
                    MessageUtil.sendMessage(player, "§f[§c主线§f] §a你需要将主线剧情完成才能跳转场景.");
                }
            }.runTaskLater(Storyline.inst(),15L);
        }
    }
}
