package com.yaohun.wheatwar.game;

import com.io.yutian.pixelliveengine.api.PixelLiveEngineAPI;
import com.yaohun.wheatwar.WheatWar;
import com.yaohun.wheatwar.data.LikeData;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.data.Ageable;
import org.bukkit.block.data.BlockData;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import tools.BossBarUtil;
import tools.StackUtil;

import java.util.*;

public class Game {

    private World world;
    private Region region;
    private BossBar bossBar1;
    private BossBar bossBar2;
    private BossBar bossBar3;
    private boolean started = false;
    private Location centralPoint;
    private List<Location> wheatList = new ArrayList<>();
    private List<BukkitTask> tasks = new ArrayList<>();
    // 狂暴模式
    public Game(){
        this.world = Bukkit.getWorld("world");
        this.region = new Region(world,new Point(-30,68,-33),new Point(32,68,29));
        this.centralPoint = new Location(world,1,72,-2);
        this.bossBar1 = Bukkit.createBossBar("今日挑战进度", BarColor.WHITE, BarStyle.SEGMENTED_10);
        this.bossBar2 = Bukkit.createBossBar("补种进度", BarColor.GREEN, BarStyle.SEGMENTED_20);
        this.bossBar3 = Bukkit.createBossBar("点赞累积数量", BarColor.WHITE, BarStyle.SEGMENTED_10);
        initGameMapFarmland();
    }

    private void updateCompleteWheatGoalBossBar() {
        int cNow = GameSite.getMatureWheatAmount();
        int cMax = wheatList.size();
        double d = (double) cNow / (double) cMax;
        String bossTitle = "§6成熟小麦数量§c: §f"+cNow+" §b("+String.format("%.2f",(d*100))+"%)";
        bossBar2.setTitle(bossTitle);
        BossBarUtil.setBarColor(bossBar2,d);
        BossBarUtil.setBarProgress(bossBar2,d);
    }

    public void updateDianZanBossBar() {
        int dz = 0;
        int needDz = 300;
        String eventName = "";
        HashMap<String, LikeData> likeDataMap = WheatWar.getGameManager().getLikeDataMap();
        for (String key : likeDataMap.keySet()){
            LikeData likeData = likeDataMap.get(key);
            dz = likeData.getNowAmount();
            needDz = likeData.getNeedAmount();
            eventName = likeData.getEffectKey();
            break;
        }
        int dz_need = needDz;
        double dz1 = (double) dz / (double) dz_need;
        // String bossTitle = "§6"+eventName+"(戳一戳): §d"+dz+"§f/§c"+dz_need;
        String bossTitle = "§9§l"+eventName+"§6: §d"+dz+"§f/§c"+dz_need;
        bossBar3.setTitle(bossTitle);
        BossBarUtil.setBarColor(bossBar3,dz1);
        BossBarUtil.setBarProgress(bossBar3,dz1);
    }


    public void start(){
        if (started) {
            return;
        }
        this.started = true;
        tasks.add(new BukkitRunnable() {
            @Override
            public void run() {
                updateCompleteWheatGoalBossBar();
                updateDianZanBossBar();
            }
        }.runTaskTimer(WheatWar.inst(), 0L, 5L));
    }

    public int getWorldEntityAmount(EntityType entityType){
        int amount = 0;
        for (Entity entity : this.world.getEntities()){
            if(entity.getType().equals(entityType)){
                amount++;
            }
        }
        return amount;
    }

    public void initPlayerData(Player player) {
        player.setArrowCooldown(6000);
        player.setGameMode(GameMode.SURVIVAL);
        player.setAllowFlight(true);
        // bossBar1.addPlayer(player);
        bossBar2.addPlayer(player);
        bossBar3.addPlayer(player);
        initPlayerBackpack(player);
        /*tasks.add(new BukkitRunnable() {
            @Override
            public void run() {
                if(player == null || !player.isOnline()){
                    cancel();
                    return;
                }
                refreshHudMessage(player);
            }
        }.runTaskTimer(WheatWar.inst(), 0L, 5L));*/
    }
    public void refreshHudMessage(Player player){
        PixelLiveEngineAPI.clearHudText();
        List<String> stringList = new ArrayList<>();
        stringList.add("§c小羊哥: §f"+getWorldEntityAmount(EntityType.SHEEP)+"只");
        stringList.add("§b村民: §f"+getWorldEntityAmount(EntityType.VILLAGER)+"名");
        PixelLiveEngineAPI.setHudText(stringList);
    }
    public void initPlayerBackpack(Player player){
        Inventory inv = player.getInventory();
        inv.setItem(0, StackUtil.diamondSword());
        inv.setItem(1,StackUtil.trident());
        inv.setItem(2,new ItemStack(Material.WHEAT_SEEDS,32));
        inv.setItem(3,new ItemStack(Material.BONE_MEAL,32));
    }


    public Location getFarmlandRandom(){
        List<Location> locationList = getWheatList();
        Collections.shuffle(locationList);
        Random random = new Random();
        return locationList.get(random.nextInt(locationList.size()));
    }
    // 获取一个未种植小麦的坐标
    public Location getAirWheatLocation(){
        Location location = null;
        List<Location> locationList = getWheatList();
        Collections.shuffle(locationList);
        for (Location loc : locationList){
            Block block = world.getBlockAt(loc);
            if (block.getType().equals(Material.AIR)) {
                location = loc;
                break;
            }
        }
        return location;
    }
    // 获取未成熟小麦的坐标
    public Location getAgeableWheatLocation(){
        Location location = null;
        List<Location> locationList = getWheatList();
        Collections.shuffle(locationList);
        for (Location loc : locationList){
            Block block = world.getBlockAt(loc);
            if (!block.getType().equals(Material.AIR) && block.getType().equals(Material.WHEAT)) {
                BlockData blockData = block.getBlockData();
                if (blockData instanceof Ageable ageable) {
                    if (ageable.getAge() < 7) {
                        location = loc;
                        break;
                    }
                }
            }
        }
        return location;
    }

    // 获取已成熟小麦的坐标
    public Location getMatureWheatLocation(){
        Location location = null;
        List<Location> locationList = getWheatList();
        Collections.shuffle(locationList);
        for (Location loc : locationList){
            Block block = world.getBlockAt(loc);
            if (!block.getType().equals(Material.AIR) && block.getType().equals(Material.WHEAT)) {
                BlockData blockData = block.getBlockData();
                if (blockData instanceof Ageable ageable) {
                    if (ageable.getAge() == 7) {
                        location = loc;
                        break;
                    }
                }
            }
        }
        return location;
    }
    // 优先寻找未种小麦的地    已种小麦未成熟的地
    public Location getPriorityRepairLocation(){
        Location location = null;
        List<Location> locationList = getWheatList();
        Collections.shuffle(locationList);
        for (Location loc : locationList){
            Block block = world.getBlockAt(loc);
            if(!block.getType().equals(Material.AIR) && block.getType().equals(Material.WHEAT)){
                BlockData blockData = block.getBlockData();
                if (blockData instanceof Ageable ageable) {
                    if (ageable.getAge() < 7) {
                        location = loc.clone().add(0.5,0,0.5);
                        break;
                    }
                }
            }else if (block.getType().equals(Material.AIR)) {
                location = loc.clone().add(0.5,0,0.5);
                break;
            }
        }
        return location;
    }


    // 优先寻找未种小麦的地    已种小麦未成熟的地
    public Location getPriorityClearLocation(){
        Location location = null;
        List<Location> locationList = getWheatList();
        Collections.shuffle(locationList);
        for (Location loc : locationList){
            Block block = world.getBlockAt(loc);
            if(block.getType().equals(Material.WHEAT)){
                BlockData blockData = block.getBlockData();
                if (blockData instanceof Ageable ageable) {
                    if(ageable.getAge() >= 7){
                        location = loc.clone().add(0.5,0,0.5);
                        break;
                    }else if (ageable.getAge() < 5) {
                        location = loc.clone().add(0.5,0,0.5);
                        break;
                    }
                }
            }
        }
        return location;
    }

    public World getWorld() {return world;}
    public List<Location> getWheatList() {return wheatList;}
    public Region getRegion() {return region;}
    public Location getCentralPoint() {return centralPoint;}
    public boolean isStarted() {return started;}
    public void addTasks(BukkitTask task){
        this.tasks.add(task);
    }

    public void initGameMapFarmland(){
        this.world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false);
        this.world.setGameRule(GameRule.DO_WEATHER_CYCLE, false);
        this.world.setGameRule(GameRule.DO_MOB_SPAWNING, false);
        this.world.setGameRule(GameRule.DO_MOB_LOOT, false);
        this.world.setGameRule(GameRule.MOB_GRIEFING, false);
        this.world.setGameRule(GameRule.RANDOM_TICK_SPEED, 0);
        this.world.setTime(4500);
        this.world.setDifficulty(Difficulty.NORMAL);
        List<Location> locationList = new ArrayList<>();
        for (int y = (int) Math.floor(67); y <= 67; y++) {
            for (int x = (int) Math.floor(region.getMin().getX()); x <= region.getMax().getX(); x++) {
                for (int z = (int) Math.floor(region.getMin().getZ()); z <= region.getMax().getZ(); z++) {
                    Block block = region.getWorld().getBlockAt(x, y, z);
                    if (!block.getType().equals(Material.AIR)) {
                        if(block.getType().equals(Material.FARMLAND)){
                            locationList.add(block.getLocation().clone().add(0,1,0));
                        }
                    }
                }
            }
        }
        this.wheatList = locationList;
        Bukkit.getConsoleSender().sendMessage("[日志 - 保卫小麦] 游戏地图:");
        Bukkit.getConsoleSender().sendMessage(" - "+this.wheatList.size()+"块小麦");
    }
}
