package net.kyau.darkmatter.items;

import java.util.List;

import org.lwjgl.input.Keyboard;

import net.kyau.darkmatter.DarkMatterMod;
import net.kyau.darkmatter.dimension.TeleporterVoid;
import net.kyau.darkmatter.references.ModInfo;
import net.kyau.darkmatter.references.Ref;
import net.kyau.darkmatter.registry.ModSounds;
import net.kyau.darkmatter.sound.SoundHelper;
import net.kyau.darkmatter.utils.ChatUtil;
import net.kyau.darkmatter.utils.ItemHelper;
import net.kyau.darkmatter.utils.LogHelper;
import net.kyau.darkmatter.utils.NBTHelper;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class VoidPearl extends BaseItem {

  public static int cooldown = Ref.ItemCooldown.VOIDPEARL;

  public VoidPearl() {
    super();
    //this.setUnlocalizedName(Ref.ItemID.VOIDPEARL);
    setCreativeTab(DarkMatterMod.DarkMatterTab);
  }

  @Override
  public EnumAction getItemUseAction(ItemStack stack) {
      return EnumAction.NONE;
  }

  @Override
  public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
    boolean firstUse = false;
    ItemStack stack = player.getHeldItem(hand);
    NBTTagCompound playerNBT = player.getEntityData();
    // Set an Owner, if one doesn't exist already
    if (!ItemHelper.hasOwnerUUID(stack)) {
      ItemHelper.setOwner(stack, player);
      if (!world.isRemote)
        ChatUtil.sendNoSpam(player, new TextComponentTranslation(Ref.Translation.IMPRINT_SUCCESS));
      firstUse = true;
    }
    // Set a UUID, if one doesn't exist already
    if (!NBTHelper.hasUUID(stack)) {
      NBTHelper.setUUID(stack);
    }
    // Set a LastUse, if one doesn't exist already
    if (!playerNBT.hasKey(Ref.NBT.LASTUSE)) {
      playerNBT.setLong(Ref.NBT.LASTUSE, player.world.getTotalWorldTime() - (cooldown + 10));
    }
    // if (!NBTHelper.hasTag(stack, Ref.NBT.LASTUSE)) {
    // NBTHelper.setLastUse(stack, player.worldObj.getTotalWorldTime() - (cooldown + 10));
    // }

    if (firstUse)
      return new ActionResult<ItemStack>(EnumActionResult.PASS, stack);

    final String owner = ItemHelper.getOwnerName(stack);
    // invalid ownership
    if (!owner.equals(player.getDisplayNameString())) {
      ChatUtil.sendNoSpam(player, Ref.Translation.IMPRINT_SCAN_FAILED);
      if (!world.isRemote) {
        SoundHelper.playSound(world, player, ModSounds.ERROR, 0.5F, 1.0F);
      }
      return new ActionResult<ItemStack>(EnumActionResult.FAIL, stack);
    }

    DimensionManager dm = new DimensionManager();
    World overworld = dm.getWorld(0);
    //PlayerProperties props = PlayerProperties.get(player);
    //long currentTime = player.world.getTotalWorldTime();
    //long lastUse = props.getCooldown();
    //long lastUse = 0;
    //long ticksSinceLastUse = currentTime - lastUse;

    //if (ModInfo.DEBUG)
      //LogHelper.info("> DEBUG: ticksSinceLastUse: " + ticksSinceLastUse + "." + cooldown);
    //if (ticksSinceLastUse > cooldown || ticksSinceLastUse < 0) {
      // Get the Overworld world object
      BlockPos playerHome = player.getBedLocation(0);
      boolean spawnpoint = false;

      // If player has no bed, set the destination to server spawn
      if (playerHome == null) {
        spawnpoint = true;
        if (!world.isRemote) {
          playerHome = overworld.getSpawnPoint();
        } else {
          playerHome = player.world.getSpawnPoint();
        }
      }

      if (!world.isRemote) {
        IBlockState state = overworld.getBlockState(playerHome);
        Block block = (state == null) ? null : overworld.getBlockState(playerHome).getBlock();
        if (block != null && !spawnpoint) {
          if (block.equals(Blocks.BED) || block.isBed(state, overworld, playerHome, player)) {
            // Reposition player according to where bed wants the player to spawn
            playerHome = block.getBedSpawnPosition(state, overworld, playerHome, null);
          } else {
            player.sendMessage(new TextComponentTranslation("Your bed was missing or obstructed."));
            return new ActionResult<ItemStack>(EnumActionResult.FAIL, stack);
          }
        } else if (block == null) {
          player.sendMessage(new TextComponentTranslation(TextFormatting.RED + "ERROR: No spawn or bed location found!"));
          return new ActionResult<ItemStack>(EnumActionResult.FAIL, stack);
        }

        // Trigger cooldown and send client packet
        long time = overworld.getTotalWorldTime();
        //props.setCooldown(time);

        // Destination exists, teleport the player
        EntityPlayerMP playerMP = (EntityPlayerMP) player;
        // Make sure destination is clean
        while (overworld.getBlockState(playerHome).getBlock().isOpaqueCube(state))
          playerHome = playerHome.up(2);
        // Issue teleport
        if (!(playerMP.dimension == 1)) {
          if (playerMP.dimension != 0) {
            world.getMinecraftServer().getPlayerList().transferPlayerToDimension(playerMP, 0, new TeleporterVoid(playerMP.mcServer.worldServerForDimension(0)));
          }

          player.setPositionAndUpdate(playerHome.getX(), playerHome.getY(), playerHome.getZ());
          player.fallDistance = 0F;
          //MinecraftServer.getServer().worldServerForDimension(playerMP.dimension).playSoundEffect(player.posX, player.posY, player.posZ, "mob.endermen.portal", 1.0F, 1.0F);
          SoundHelper.playSound(world, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_ENDERMEN_TELEPORT, SoundCategory.HOSTILE, 1.0F, 1.0F);
        }
      }
      return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, stack);
    /*
    } else {
      if (player.dimension == 1 && owner.equals(player.getDisplayNameString())) {
        SoundHelper.playSound(world, player, ModSounds.ERROR, 0.5F, 1.0F);
      } else if (ticksSinceLastUse > 0 && ticksSinceLastUse < cooldown) {
        SoundHelper.playSound(world, player, ModSounds.ERROR, 0.5F, 1.0F);
      }
    }
    return new ActionResult<ItemStack>(EnumActionResult.FAIL, stack);
    */
  }

  @Override
  @SideOnly(Side.CLIENT)
  public void addInformation(ItemStack stack, EntityPlayer player, List<String> tooltip, boolean advanced) {
    // Item Stats
    if (!ItemHelper.hasOwner(stack)) {
      tooltip.add(I18n.format(Ref.Translation.PREIMPRINT));
    }
    // Description
    if (Keyboard.isKeyDown(0x2A) || Keyboard.isKeyDown(0x36)) {
      tooltip.add(TextFormatting.GRAY + "This device may be used to transport");
      tooltip.add(TextFormatting.GRAY + "you across dimensions to your home.");
    } else {
      tooltip.add(I18n.format(Ref.Translation.MORE_INFORMATION));
    }
    // Owner information
    if (ItemHelper.hasOwner(stack)) {
      final String owner = ItemHelper.getOwnerName(stack);

      if (owner.equals(player.getDisplayNameString())) {
        tooltip.add(TextFormatting.GREEN + I18n.format(Ref.Translation.OWNER) + " " + owner);
        /*
        long lastUse = DarkMatterMod.proxy.getVoidPearlLastUse();
        if (lastUse != -1) {
          long currentTime = player.world.getTotalWorldTime();
          long ticksSinceLastUse = currentTime - lastUse;
          // LogHelper.info("Worldtime: " + currentTime + " / Last Use: " + lastUse);
          if (ticksSinceLastUse < cooldown) {
            long current = (cooldown / 20) - (ticksSinceLastUse / 20);
            String currentCooldown = ItemHelper.formatCooldown(current);
            tooltip.add(I18n.format(Ref.Translation.COOLDOWN) + " " + currentCooldown);
          }
        }
        */
      } else {
        if (ModInfo.DEBUG) {
          tooltip.add(TextFormatting.RED + I18n.format(Ref.Translation.OWNER) + " " + owner);
        } else {
          tooltip.add(TextFormatting.RED + I18n.format(Ref.Translation.OWNER) + " " + TextFormatting.OBFUSCATED + owner);
        }
      }
    }
    super.addInformation(stack, player, tooltip, advanced);
  }

}