<?php

namespace bedwars\entity;

use pocketmine\Player;

use pocketmine\item\Item;
use pocketmine\item\enchantment\Enchantment;

use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\StringTag;
use pocketmine\nbt\tag\IntTag;

use bedwars\BedWars;
use bedwars\inventory\Inventory;

use pocketmine\level\sound\ExpPickupSound;
use pocketmine\level\sound\SplashSound;

use bedWars\game\Game;
use bedwars\util\Team;

class Upgrade extends VillagerNPC {
    
    /** @var int */
    public $type = 15;

    /** @var array */
    public $nametag = ["§r§b§lUPGRADE SHOP", "§eRight Click"];
    
    const MENU = array(
        "forge" => array("§r§eForge", " §r§fWith each upgrade ur generator will become more faster and alot of more ores will come", 61, 0, 3),
        "miner" => array("§r§fHaste", " §r§fAt each haste level\n You can mine blocks faster and faster!!", 285, 0, 4),
        "sharp" => array("§r§eSharp", " §r§fThis upgrade will increase ur damage!!", 267, 0, 4),
        "armor" => array("§r§fArmor", " §r§fUpgrading this will give you projection\n Each level is a higher level of projection!", 307, 0, 4),
        "trap" => array("§r§7Trap", " §r§fYou will get informed when someone steps into ur base\n upgrading this will give them effects which will slow them down\n and help you fight them!", 131, 0, 4),
        "força" => array("§r§cStrength", " §r§f!Strength will give you a higher damage hit\n upgrading this can really be overpowered", 256, 0, 4),
        "regen" => array("§r§cRegeneration", "§r§fAt each level of regeneration, you will recover hp easily\n On ur island!!", 370, 0, 4)
    );
    
    const ICONS = array();
    
    /**
    * @param Player $player
    */
    public function open(Player $player) {
        $game = BedWars::$loaded->getGame($player);

        if (!($game instanceof Game)) {
            $player->sendMessage("§cThe upgrade shop is only available in-game!");
            return false;
        }
        
        if ($game->index != 3) {
            $player->sendMessage("§cYou can only see the upgrade shop when the match starts!");
            return false;
        }
        
        if (isset($game->espects[$player->getName()]) or isset($game->respawn[$player->getName()])) {
            $player->sendMessage("§cPlayers in spectator mode cannot open the upgrade shop!");
            return false;
        }
        
        $team = $game->getTeam($player->getName());
        
        $inventory = new Inventory($player, "§r§l§dUPGRADE§r");
        $player->addWindow($inventory);
        
        $this->addMenu($player, $inventory, $team, $game);
        
        $inventory->addEvent($player, function(Player $player, Item $item, $inventory) {
            $game = BedWars::$loaded->getGame($player);

            if (!($game instanceof Game)) {
                return false;
            }
        
            $team = $game->getTeam($player->getName());
            $namedtag = $item->getNamedTag();
            
            if ($namedtag instanceof CompoundTag) {
                if (isset($namedtag["Type"], $namedtag["Price"], $namedtag["ItemName"])) {
                    $type = $namedtag["Type"];
                    $price = $namedtag["Price"];
                    $itemName = $namedtag["ItemName"];
                    $level = $this->getUpLevel($type, $team->getName(), $game);
                    $count = 0;
                        
                    foreach ($player->getInventory()->getContents() as $slot => $itemI) {
                        if ($itemI->getId() == 264) {
                            $count += $itemI->getCount();
                            
                            if ($count >= $price) {
                                break;
                            }
                        }
                    }

                    if ($level++ < 3) {
                        if ($count >= $price) {
                            $game->upgrade[$team->getName()][$type] = $level;
                            $game->updateItems($team->getName());
                            
                            $player->sendMessage("§r§aYou bought the " . $itemName . " §r§aUpgrade and is now " . $level);
                            
                            foreach ($team->getPlayers() as $value) {
                                if (!($value instanceof Player)) {
                                    continue;
                                }
                                
                                $value->sendMessage("§r\n§a" . $player->getNameTag() . "§a upgraded the " . $itemName . " §aupgrade and it is now " . $level . "!§r\n");
                            }

                            $this->addMenu($player, $inventory, $team, $game);
                            
                            $player->level->addSound(new ExpPickupSound($player), array($player));
                            $player->getInventory()->removeItem(Item::get(264, 0, $price));
                            return true;
                        } else {
                            $player->sendMessage("§r§cYou don't have enough items, you are missing: " . ($price - $count) . " §bdiamonds§r§c!");
                        }
                    } else {
                        $player->sendMessage("§r§cThat is the maximum you can upgrade " . $itemName . "§r§c It is now at its top level");
                    }
                    $player->removeWindow($inventory);
                    $player->level->addSound(new SplashSound($player), array($player));
                }
            }
        });
        return true;
    }
    
    /**
    * @param Player    $player 
    * @param Inventory $inventory
    * @param Team      $team
    */
    public function addMenu(Player $player, $inventory, Team $team, Game $game) {
        $contents = array();
        $slot = 0;

        foreach (Upgrade::MENU as $type => $args) {
            $level = $this->getUpLevel($type, $team->getName(), $game);
            $item = Item::get($args[2], $args[3], (int) ($level == 0 ? 1 : $level));
            
            if ($item->getId() === 0 && $args[2] !== 0) {
                 // Skip invalid items if Item::get returned Air but ID wasn't 0
                 // This protects against ID 498 if it wasn't fixed or other invalid IDs
                 continue;
            }

            // Removed unsafe enchantment -1 call that crashes Genisys/PMMP 2.0
            /*
            if ($level >= 3) {
                $item->addEnchantment(Enchantment::getEnchantment(-1)->setLevel(0));
            }
            */

            $price = $args[4] * ($level > 0 ? ($level + 1) : 1);
            $lines = explode("\n", $args[0]);
            $lines[1] = $args[1];
            $lines[3] = "§r§8Price:§b " . $price . " Diamonds" . "§r§a " . $level . "/3";
            //$lines[4] = $this->getLevelFormat($level);
            $item->setCustomName(implode("\n", $lines));
            $nbt = $item->getNamedTag();
            $nbt->Type = new StringTag("Type", $type);
            $nbt->Price = new IntTag("Price", $price);
            $nbt->ItemName = new StringTag("ItemName", $args[0]);
            $item->setNamedtag($nbt);
            
            $contents[$slot++] = $item;
        }
        $inventory->setContents($contents);
    }
    
    /**
    * @param string $type
    * @param string $team
    * @param Game $game 
    */
    private function getUpLevel(string $type, string $team, Game $game) {
        if (isset($game->upgrade[$team])) {
            if (isset($game->upgrade[$team][$type])) {
                return $game->upgrade[$team][$type];
            }
        }
        return 0;
    }
    
    /**
    * @param int $level
    * @return string
    */
    private function getLevelFormat(int $level) {
        $amount = 15;
        $stick = "§7" . str_repeat("▌", $amount);
        $format = array($stick, $stick, $stick);
        
        for ($i = 1; $i <= 2; $i++) {
            if ($i >= $level) {
                $format[$i] = "§a" . $format[1];
            }
        }
        return (implode("§r\n§r", $format));
    }
}
?>
