package com.yaohun.wheatwar.listener;

import com.io.yutian.pixelliveengine.api.PixelLiveEngineAPI;
import com.yaohun.wheatwar.WheatWar;
import com.yaohun.wheatwar.data.RepairGiftGui;
import com.yaohun.wheatwar.game.Game;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.scheduler.BukkitRunnable;
import tools.RandomUtil;

public class JoinListener implements Listener {

    @EventHandler
    public void onJoin(PlayerJoinEvent e){
        Player player = e.getPlayer();
        Game game = WheatWar.getGame();
        new BukkitRunnable() {
            @Override
            public void run() {
                if(!game.isStarted()) {
                    game.start();
                }
                player.teleport(new Location(player.getWorld(),3.5,68,32.5,-180,0));
                game.initPlayerData(e.getPlayer());
            }
        }.runTaskLater(WheatWar.inst(),10L);
        new BukkitRunnable() {
            @Override
            public void run() {
                PixelLiveEngineAPI.loadResourcePack("SoundPack5","rvHbB9FdOxWYAfi8kTLe");
            }
        }.runTaskLater(WheatWar.inst(),20L);
    }

    @EventHandler
    public void onPick(PlayerDropItemEvent e){
        Player p = e.getPlayer();
        if (WheatWar.getGame().isStarted()) {
            if(p.isSneaking()){
                RepairGiftGui.OpenGui(p);
            }
        }
    }

    @EventHandler
    public void onAutoRespawn(PlayerDeathEvent e) {
        e.setDeathMessage(null);
        Player p = e.getEntity();
        // 获取当前游戏记录点高度
        Game game = WheatWar.getGame();
        if (game.isStarted()) {
            new BukkitRunnable() {
                private int i = 0;

                public void run() {
                    if (i == 1) {
                        p.spigot().respawn();
                    }
                    if(i == 3){
                        p.getInventory().clear();
                    }
                    if(i == 4) {
                        if (RandomUtil.getRandomInt(1,100) >= 50) {
                            p.sendTitle("§4你嘎了", "行不行啊？菜就多练！");
                        } else {
                            p.sendTitle("§4你嘎了", "汗流浃背了？");
                        }
                        game.initPlayerBackpack(p);
                    }
                    if(i == 5) {
                        p.teleport(new Location(p.getWorld(),3.5,68,32.5,-180,0));
                        if(!p.getAllowFlight()){
                            p.setAllowFlight(true);
                        }
                        cancel();
                    }
                    i++;
                }
            }.runTaskTimer(WheatWar.inst(),0L, 2L);
        }
    }
}
