package common.item.block;

import common.block.Block;
import common.block.artificial.BlockBed;
import common.entity.npc.EntityNPC;
import common.item.CheatTab;
import common.item.Item;
import common.item.ItemStack;
import common.util.BlockPos;
import common.util.ExtMath;
import common.util.Facing;
import common.world.State;
import common.world.World;

public class ItemBed extends Item
{
	private final BlockBed bedBlock;
	
    public ItemBed(BlockBed bedBlock)
    {
    	this.bedBlock = bedBlock;
        this.setTab(CheatTab.DECORATION);
        this.setMaxAmount(1);
    }

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

    /**
     * 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 (worldIn.client)
        {
            return true;
        }
        else if (side != Facing.UP)
        {
            return false;
        }
        else
        {
            State iblockstate = worldIn.getState(pos);
            Block block = iblockstate.getBlock();
            boolean flag = block.isReplaceable(worldIn, pos);

            if (!flag)
            {
                pos = pos.up();
            }

            int i = ExtMath.floord((double)(playerIn.rotYaw * 4.0F / 360.0F) + 0.5D) & 3;
            Facing enumfacing = Facing.getHorizontal(i);
            BlockPos blockpos = pos.offset(enumfacing);

            if (playerIn.canPlayerEdit(pos, side, stack) && playerIn.canPlayerEdit(blockpos, side, stack))
            {
                boolean flag1 = worldIn.getState(blockpos).getBlock().isReplaceable(worldIn, blockpos);
                boolean flag2 = flag || worldIn.isAirBlock(pos);
                boolean flag3 = flag1 || worldIn.isAirBlock(blockpos);

                if (flag2 && flag3 && worldIn.isBlockSolid(pos.down()) && worldIn.isBlockSolid(blockpos.down()))
                {
                    State iblockstate1 = this.bedBlock.getState() /* .withProperty(BlockBed.OCCUPIED, Boolean.valueOf(false)) */ .withProperty(BlockBed.FACING, enumfacing).withProperty(BlockBed.PART, BlockBed.EnumPartType.FOOT);

                    if (worldIn.setState(pos, iblockstate1, 3))
                    {
                        State iblockstate2 = iblockstate1.withProperty(BlockBed.PART, BlockBed.EnumPartType.HEAD);
                        worldIn.setState(blockpos, iblockstate2, 3);
                    }

                    --stack.size;
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    }
}
