package common.item.block;

import common.block.Block;
import common.block.tile.BlockStandingSign;
import common.block.tile.BlockWallSign;
import common.entity.npc.EntityNPC;
import common.init.Blocks;
import common.item.CheatTab;
import common.item.Item;
import common.item.ItemStack;
import common.tileentity.TileEntity;
import common.tileentity.TileEntitySign;
import common.util.BlockPos;
import common.util.ExtMath;
import common.util.Facing;
import common.world.World;

public class ItemSign extends Item
{
	private final BlockStandingSign block;
	
    public ItemSign(BlockStandingSign block)
    {
    	this.block = block;
        this.setTab(CheatTab.DECORATION);
    }

    public Block getBlock()
    {
        return this.block;
    }

    /**
     * Called when a Block is right-clicked with this Item
     */
    public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ)
    {
        if (side == Facing.DOWN)
        {
            return false;
        }
        else if (!worldIn.getState(pos).getBlock().getMaterial().isSolid())
        {
            return false;
        }
        else
        {
            pos = pos.offset(side);

            if (!playerIn.canPlayerEdit(pos, side, stack))
            {
                return false;
            }
            else if (!this.block.canPlaceBlockAt(worldIn, pos))
            {
                return false;
            }
            else if (worldIn.client)
            {
                return true;
            }
            else
            {
                if (side == Facing.UP)
                {
                    int i = ExtMath.floord((double)((playerIn.rotYaw + 180.0F) * 16.0F / 360.0F) + 0.5D) & 15;
                    worldIn.setState(pos, Blocks.sign.getState().withProperty(BlockStandingSign.ROTATION, Integer.valueOf(i)), 3);
                }
                else
                {
                    worldIn.setState(pos, Blocks.wall_sign.getState().withProperty(BlockWallSign.FACING, side), 3);
                }

                --stack.size;
                TileEntity tileentity = worldIn.getTileEntity(pos);

                if (tileentity instanceof TileEntitySign && !ItemBlock.setTileEntityNBT(worldIn, playerIn, pos, stack))
                {
                    playerIn.openEditSign((TileEntitySign)tileentity);
                }

                return true;
            }
        }
    }
}
