package common.block.artificial;

import common.block.Block;
import common.block.Rotatable;
import common.block.Material;
import common.entity.npc.EntityNPC;
import common.entity.types.EntityLiving;
import common.init.Blocks;
import common.item.CheatTab;
import common.model.BlockLayer;
import common.model.Model;
import common.model.ModelProvider;
import common.model.ModelRotation;
import common.model.Transforms;
import common.properties.Property;
import common.properties.PropertyBool;
import common.properties.PropertyEnum;
import common.util.BlockPos;
import common.util.BoundingBox;
import common.util.Facing;
import common.util.HitPosition;
import common.util.Identifyable;
import common.util.Vec3;
import common.world.IBlockAccess;
import common.world.IWorldAccess;
import common.world.State;
import common.world.World;

public class BlockTrapDoor extends Block implements Rotatable
{
    public static final PropertyBool OPEN = PropertyBool.create("open");
    public static final PropertyEnum<BlockTrapDoor.DoorHalf> HALF = PropertyEnum.<BlockTrapDoor.DoorHalf>create("half", BlockTrapDoor.DoorHalf.class);

    public BlockTrapDoor(Material materialIn)
    {
        super(materialIn);
        this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(OPEN, Boolean.valueOf(false)).withProperty(HALF, BlockTrapDoor.DoorHalf.BOTTOM));
        float f = 0.5F;
        float f1 = 1.0F;
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
        this.setTab(materialIn == Material.WOOD ? CheatTab.WOOD : CheatTab.TECHNOLOGY);
    }

    /**
     * Used to determine ambient occlusion and culling when rebuilding chunks for render
     */
    public boolean isOpaqueCube()
    {
        return false;
    }

    public boolean isFullCube()
    {
        return false;
    }

    public boolean isPassable(IBlockAccess worldIn, BlockPos pos)
    {
        return !((Boolean)worldIn.getState(pos).getValue(OPEN)).booleanValue();
    }

    public BoundingBox getSelectedBoundingBox(World worldIn, BlockPos pos)
    {
        this.setBlockBoundsBasedOnState(worldIn, pos);
        return super.getSelectedBoundingBox(worldIn, pos);
    }

    public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state)
    {
        this.setBlockBoundsBasedOnState(worldIn, pos);
        return super.getCollisionBoundingBox(worldIn, pos, state);
    }

    public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos)
    {
        this.setBounds(worldIn.getState(pos));
    }

    /**
     * Sets the block's bounds for rendering it as an item
     */
    public void setBlockBoundsForItemRender()
    {
        float f = 0.1875F;
        this.setBlockBounds(0.0F, 0.40625F, 0.0F, 1.0F, 0.59375F, 1.0F);
    }

    public void setBounds(State state)
    {
        if (state.getBlock() == this)
        {
            boolean flag = state.getValue(HALF) == BlockTrapDoor.DoorHalf.TOP;
            Boolean obool = (Boolean)state.getValue(OPEN);
            Facing enumfacing = (Facing)state.getValue(FACING);
            float f = 0.1875F;

            if (flag)
            {
                this.setBlockBounds(0.0F, 0.8125F, 0.0F, 1.0F, 1.0F, 1.0F);
            }
            else
            {
                this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.1875F, 1.0F);
            }

            if (obool.booleanValue())
            {
                if (enumfacing == Facing.NORTH)
                {
                    this.setBlockBounds(0.0F, 0.0F, 0.8125F, 1.0F, 1.0F, 1.0F);
                }

                if (enumfacing == Facing.SOUTH)
                {
                    this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.1875F);
                }

                if (enumfacing == Facing.WEST)
                {
                    this.setBlockBounds(0.8125F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
                }

                if (enumfacing == Facing.EAST)
                {
                    this.setBlockBounds(0.0F, 0.0F, 0.0F, 0.1875F, 1.0F, 1.0F);
                }
            }
        }
    }

    public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ)
    {
        if (this.material == Material.SOLID)
        {
            return true;
        }
        else
        {
            state = state.cycleProperty(OPEN);
            worldIn.setState(pos, state, 2);
            worldIn.playAuxSFX(playerIn, ((Boolean)state.getValue(OPEN)).booleanValue() ? 1003 : 1006, pos, 0);
            return true;
        }
    }

    /**
     * Called when a neighboring block changes.
     */
    public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock)
    {
        if (!worldIn.client)
        {
            BlockPos blockpos = pos.offset(((Facing)state.getValue(FACING)).getOpposite());

            if (!isValidSupportBlock(worldIn.getState(blockpos).getBlock()))
            {
                worldIn.setBlockToAir(pos);
                this.dropBlockAsItem(worldIn, pos, state, 0);
            }
            else
            {
                boolean flag = worldIn.isBlockPowered(pos);

                if (flag || neighborBlock.canProvidePower())
                {
                    boolean flag1 = ((Boolean)state.getValue(OPEN)).booleanValue();

                    if (flag1 != flag)
                    {
                        worldIn.setState(pos, state.withProperty(OPEN, Boolean.valueOf(flag)), 2);
                        worldIn.playAuxSFX(flag ? 1003 : 1006, pos, 0);
                    }
                }
            }
        }
    }

    /**
     * Ray traces through the blocks collision from start vector to end vector returning a ray trace hit.
     */
    public HitPosition collisionRayTrace(World worldIn, BlockPos pos, Vec3 start, Vec3 end)
    {
        this.setBlockBoundsBasedOnState(worldIn, pos);
        return super.collisionRayTrace(worldIn, pos, start, end);
    }

    /**
     * Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the
     * IBlockstate
     */
    public State onBlockPlaced(World worldIn, BlockPos pos, Facing facing, float hitX, float hitY, float hitZ, EntityLiving placer)
    {
        State iblockstate = this.getState();

        if (facing.getAxis().isHorizontal())
        {
            iblockstate = iblockstate.withProperty(FACING, facing).withProperty(OPEN, Boolean.valueOf(false));
            iblockstate = iblockstate.withProperty(HALF, hitY > 0.5F ? BlockTrapDoor.DoorHalf.TOP : BlockTrapDoor.DoorHalf.BOTTOM);
        }

        return iblockstate;
    }

    /**
     * Check whether this Block can be placed on the given side
     */
    public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, Facing side)
    {
        return !side.getAxis().isVertical() && isValidSupportBlock(worldIn.getState(pos.offset(side.getOpposite())).getBlock());
    }

    protected static Facing getFacing(int meta)
    {
        switch (meta & 3)
        {
            case 0:
                return Facing.NORTH;

            case 1:
                return Facing.SOUTH;

            case 2:
                return Facing.WEST;

            case 3:
            default:
                return Facing.EAST;
        }
    }

    protected static int getMetaForFacing(Facing facing)
    {
        switch (facing)
        {
            case NORTH:
                return 0;

            case SOUTH:
                return 1;

            case WEST:
                return 2;

            case EAST:
            default:
                return 3;
        }
    }

    private static boolean isValidSupportBlock(Block blockIn)
    {
        return blockIn.getMaterial().isOpaque() && blockIn.isFullCube() || blockIn == Blocks.glass || blockIn instanceof BlockStainedGlass || blockIn == Blocks.glowstone || blockIn instanceof BlockSlab || blockIn instanceof BlockStairs;
    }

    public BlockLayer getBlockLayer()
    {
        return BlockLayer.CUTOUT;
    }

    /**
     * Convert the given metadata into a BlockState for this Block
     */
    public State getStateFromMeta(int meta)
    {
        return this.getState().withProperty(FACING, getFacing(meta)).withProperty(OPEN, Boolean.valueOf((meta & 4) != 0)).withProperty(HALF, (meta & 8) == 0 ? BlockTrapDoor.DoorHalf.BOTTOM : BlockTrapDoor.DoorHalf.TOP);
    }

    /**
     * Convert the BlockState into the correct metadata value
     */
    public int getMetaFromState(State state)
    {
        int i = 0;
        i = i | getMetaForFacing((Facing)state.getValue(FACING));

        if (((Boolean)state.getValue(OPEN)).booleanValue())
        {
            i |= 4;
        }

        if (state.getValue(HALF) == BlockTrapDoor.DoorHalf.TOP)
        {
            i |= 8;
        }

        return i;
    }

    protected Property[] getProperties()
    {
        return new Property[] {FACING, OPEN, HALF};
    }
    
    public boolean isMagnetic() {
    	return this.material == Material.SOLID;
    }

    public Transforms getTransform() {
    	return Transforms.FLAT;
    }

    public Model getModel(ModelProvider provider, String name, State state) {
    	Model model;
    	if(state.getValue(OPEN)) {
    		model = provider.getModel(name)
    				.add(0, 0, 13, 16, 16, 16)
    				.d().uv(0, 13, 16, 16)
    				.u().uv(0, 16, 16, 13)
    				.n().uv(0, 0, 16, 16).noCull()
    				.s().uv(0, 0, 16, 16)
    				.w().uv(16, 0, 13, 16)
    				.e().uv(13, 0, 16, 16);
    	}
    	else if(state.getValue(HALF) == DoorHalf.TOP) {
    		model = provider.getModel(name)
    				.add(0, 13, 0, 16, 16, 16)
    				.d().uv(0, 0, 16, 16).noCull()
    				.u().uv(0, 0, 16, 16)
    				.n().uv(0, 16, 16, 13)
    				.s().uv(0, 16, 16, 13)
    				.w().uv(0, 16, 16, 13)
    				.e().uv(0, 16, 16, 13);
    	}
    	else {
    		model = provider.getModel(name)
    				.add(0, 0, 0, 16, 3, 16)
    				.d().uv(0, 0, 16, 16)
    				.u().uv(0, 0, 16, 16).noCull()
    				.n().uv(0, 16, 16, 13)
    				.s().uv(0, 16, 16, 13)
    				.w().uv(0, 16, 16, 13)
    				.e().uv(0, 16, 16, 13);
    	}
    	return model.rotate(ModelRotation.getNorthRot(state.getValue(FACING)));
    }

    public static enum DoorHalf implements Identifyable
    {
        TOP("top"),
        BOTTOM("bottom");

        private final String name;

        private DoorHalf(String name)
        {
            this.name = name;
        }

        public String toString()
        {
            return this.name;
        }

        public String getName()
        {
            return this.name;
        }
    }
}
