package common.block.tech;

import common.block.Block;
import common.block.BlockContainer;
import common.block.Rotatable;
import common.block.Material;
import common.color.TextColor;
import common.entity.Entity;
import common.entity.animal.EntityOcelot;
import common.entity.npc.EntityNPC;
import common.entity.types.EntityLiving;
import common.init.Items;
import common.init.SoundEvent;
import common.inventory.Container;
import common.inventory.IInventory;
import common.inventory.InventoryHelper;
import common.inventory.InventoryLargeChest;
import common.item.CheatTab;
import common.item.Item;
import common.item.ItemStack;
import common.item.block.ItemChest;
import common.packet.SPacketSoundEffect;
import common.properties.Property;
import common.tileentity.ILockableContainer;
import common.tileentity.Passcode;
import common.tileentity.TileEntity;
import common.tileentity.TileEntityChest;
import common.util.BlockPos;
import common.util.BoundingBox;
import common.util.ExtMath;
import common.util.Facing;
import common.vars.Vars;
import common.world.IWorldAccess;
import common.world.State;
import common.world.World;
import common.world.AWorldServer;

public class BlockChest extends BlockContainer implements Rotatable
{
    public final int chestType;

    public BlockChest(int type)
    {
        super(Material.WOOD);
        this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH));
        this.chestType = type;
        this.setTab(CheatTab.TECHNOLOGY);
        this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F);
    }

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

    public boolean isFullCube()
    {
        return false;
    }

    /**
     * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render
     */
    public int getRenderType()
    {
        return 2;
    }

    public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos)
    {
        if (worldIn.getState(pos.north()).getBlock() == this)
        {
            this.setBlockBounds(0.0625F, 0.0F, 0.0F, 0.9375F, 0.875F, 0.9375F);
        }
        else if (worldIn.getState(pos.south()).getBlock() == this)
        {
            this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 1.0F);
        }
        else if (worldIn.getState(pos.west()).getBlock() == this)
        {
            this.setBlockBounds(0.0F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F);
        }
        else if (worldIn.getState(pos.east()).getBlock() == this)
        {
            this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 1.0F, 0.875F, 0.9375F);
        }
        else
        {
            this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F);
        }
    }

    public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state)
    {
        this.checkForSurroundingChests(worldIn, pos, state);

        for (Facing enumfacing : Facing.Plane.HORIZONTAL)
        {
            BlockPos blockpos = pos.offset(enumfacing);
            State iblockstate = worldIn.getState(blockpos);

            if (iblockstate.getBlock() == this)
            {
                this.checkForSurroundingChests(worldIn, blockpos, iblockstate);
            }
        }
    }

    /**
     * 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)
    {
        return this.getState().withProperty(FACING, placer.getHorizontalFacing());
    }

    /**
     * Called by ItemBlocks after a block is set in the world, to allow post-place logic
     */
    public void onBlockPlacedBy(World worldIn, BlockPos pos, State state, EntityLiving placer, ItemStack stack)
    {
        Facing enumfacing = Facing.getHorizontal(ExtMath.floord((double)(placer.rotYaw * 4.0F / 360.0F) + 0.5D) & 3).getOpposite();
        state = state.withProperty(FACING, enumfacing);
        BlockPos blockpos = pos.north();
        BlockPos blockpos1 = pos.south();
        BlockPos blockpos2 = pos.west();
        BlockPos blockpos3 = pos.east();
        boolean flag = this == worldIn.getState(blockpos).getBlock();
        boolean flag1 = this == worldIn.getState(blockpos1).getBlock();
        boolean flag2 = this == worldIn.getState(blockpos2).getBlock();
        boolean flag3 = this == worldIn.getState(blockpos3).getBlock();

        if (!flag && !flag1 && !flag2 && !flag3)
        {
            worldIn.setState(pos, state, 3);
        }
        else if (enumfacing.getAxis() != Facing.Axis.X || !flag && !flag1)
        {
            if (enumfacing.getAxis() == Facing.Axis.Z && (flag2 || flag3))
            {
                if (flag2)
                {
                    worldIn.setState(blockpos2, state, 3);
                }
                else
                {
                    worldIn.setState(blockpos3, state, 3);
                }

                worldIn.setState(pos, state, 3);
            }
        }
        else
        {
            if (flag)
            {
                worldIn.setState(blockpos, state, 3);
            }
            else
            {
                worldIn.setState(blockpos1, state, 3);
            }

            worldIn.setState(pos, state, 3);
        }

        if (stack.hasDisplayName())
        {
            TileEntity tileentity = worldIn.getTileEntity(pos);

            if (tileentity instanceof TileEntityChest)
            {
                ((TileEntityChest)tileentity).setCustomName(stack.getDisplayName());
            }
        }
    }

    public State checkForSurroundingChests(World worldIn, BlockPos pos, State state)
    {
        if (worldIn.client)
        {
            return state;
        }
        else
        {
            State iblockstate = worldIn.getState(pos.north());
            State iblockstate1 = worldIn.getState(pos.south());
            State iblockstate2 = worldIn.getState(pos.west());
            State iblockstate3 = worldIn.getState(pos.east());
            Facing enumfacing = (Facing)state.getValue(FACING);
            Block block = iblockstate.getBlock();
            Block block1 = iblockstate1.getBlock();
            Block block2 = iblockstate2.getBlock();
            Block block3 = iblockstate3.getBlock();

            if (block != this && block1 != this)
            {
                boolean flag = block.isFullBlock();
                boolean flag1 = block1.isFullBlock();

                if (block2 == this || block3 == this)
                {
                    BlockPos blockpos1 = block2 == this ? pos.west() : pos.east();
                    State iblockstate6 = worldIn.getState(blockpos1.north());
                    State iblockstate7 = worldIn.getState(blockpos1.south());
                    enumfacing = Facing.SOUTH;
                    Facing enumfacing2;

                    if (block2 == this)
                    {
                        enumfacing2 = (Facing)iblockstate2.getValue(FACING);
                    }
                    else
                    {
                        enumfacing2 = (Facing)iblockstate3.getValue(FACING);
                    }

                    if (enumfacing2 == Facing.NORTH)
                    {
                        enumfacing = Facing.NORTH;
                    }

                    Block block6 = iblockstate6.getBlock();
                    Block block7 = iblockstate7.getBlock();

                    if ((flag || block6.isFullBlock()) && !flag1 && !block7.isFullBlock())
                    {
                        enumfacing = Facing.SOUTH;
                    }

                    if ((flag1 || block7.isFullBlock()) && !flag && !block6.isFullBlock())
                    {
                        enumfacing = Facing.NORTH;
                    }
                }
            }
            else
            {
                BlockPos blockpos = block == this ? pos.north() : pos.south();
                State iblockstate4 = worldIn.getState(blockpos.west());
                State iblockstate5 = worldIn.getState(blockpos.east());
                enumfacing = Facing.EAST;
                Facing enumfacing1;

                if (block == this)
                {
                    enumfacing1 = (Facing)iblockstate.getValue(FACING);
                }
                else
                {
                    enumfacing1 = (Facing)iblockstate1.getValue(FACING);
                }

                if (enumfacing1 == Facing.WEST)
                {
                    enumfacing = Facing.WEST;
                }

                Block block4 = iblockstate4.getBlock();
                Block block5 = iblockstate5.getBlock();

                if ((block2.isFullBlock() || block4.isFullBlock()) && !block3.isFullBlock() && !block5.isFullBlock())
                {
                    enumfacing = Facing.EAST;
                }

                if ((block3.isFullBlock() || block5.isFullBlock()) && !block2.isFullBlock() && !block4.isFullBlock())
                {
                    enumfacing = Facing.WEST;
                }
            }

            state = state.withProperty(FACING, enumfacing);
            worldIn.setState(pos, state, 3);
            return state;
        }
    }

    public State correctFacing(World worldIn, BlockPos pos, State state)
    {
        Facing enumfacing = null;

        for (Facing enumfacing1 : Facing.Plane.HORIZONTAL)
        {
            State iblockstate = worldIn.getState(pos.offset(enumfacing1));

            if (iblockstate.getBlock() == this)
            {
                return state;
            }

            if (iblockstate.getBlock().isFullBlock())
            {
                if (enumfacing != null)
                {
                    enumfacing = null;
                    break;
                }

                enumfacing = enumfacing1;
            }
        }

        if (enumfacing != null)
        {
            return state.withProperty(FACING, enumfacing.getOpposite());
        }
        else
        {
            Facing enumfacing2 = (Facing)state.getValue(FACING);

            if (worldIn.getState(pos.offset(enumfacing2)).getBlock().isFullBlock())
            {
                enumfacing2 = enumfacing2.getOpposite();
            }

            if (worldIn.getState(pos.offset(enumfacing2)).getBlock().isFullBlock())
            {
                enumfacing2 = enumfacing2.rotateY();
            }

            if (worldIn.getState(pos.offset(enumfacing2)).getBlock().isFullBlock())
            {
                enumfacing2 = enumfacing2.getOpposite();
            }

            return state.withProperty(FACING, enumfacing2);
        }
    }

    public boolean canPlaceBlockAt(World worldIn, BlockPos pos)
    {
        int i = 0;
        BlockPos blockpos = pos.west();
        BlockPos blockpos1 = pos.east();
        BlockPos blockpos2 = pos.north();
        BlockPos blockpos3 = pos.south();

        if (worldIn.getState(blockpos).getBlock() == this)
        {
            if (this.isDoubleChest(worldIn, blockpos))
            {
                return false;
            }

            ++i;
        }

        if (worldIn.getState(blockpos1).getBlock() == this)
        {
            if (this.isDoubleChest(worldIn, blockpos1))
            {
                return false;
            }

            ++i;
        }

        if (worldIn.getState(blockpos2).getBlock() == this)
        {
            if (this.isDoubleChest(worldIn, blockpos2))
            {
                return false;
            }

            ++i;
        }

        if (worldIn.getState(blockpos3).getBlock() == this)
        {
            if (this.isDoubleChest(worldIn, blockpos3))
            {
                return false;
            }

            ++i;
        }

        return i <= 1;
    }

    private boolean isDoubleChest(World worldIn, BlockPos pos)
    {
        if (worldIn.getState(pos).getBlock() != this)
        {
            return false;
        }
        else
        {
            for (Facing enumfacing : Facing.Plane.HORIZONTAL)
            {
                if (worldIn.getState(pos.offset(enumfacing)).getBlock() == this)
                {
                    return true;
                }
            }

            return false;
        }
    }

    /**
     * Called when a neighboring block changes.
     */
    public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock)
    {
        super.onNeighborBlockChange(worldIn, pos, state, neighborBlock);
        TileEntity tileentity = worldIn.getTileEntity(pos);

        if (tileentity instanceof TileEntityChest)
        {
            tileentity.updateContainingBlockInfo();
        }
    }

    public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state)
    {
        TileEntity tileentity = worldIn.getTileEntity(pos);

        if (tileentity instanceof IInventory)
        {
            InventoryHelper.dropInventoryItems(worldIn, pos, (IInventory)tileentity);
            worldIn.updateComparatorOutputLevel(pos, this);
        }

        super.onBlockRemoved(worldIn, pos, state);
    }

    public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ)
    {
        if (worldIn.client)
        {
            return true;
        }
        else
        {
            ILockableContainer ilockablecontainer = this.getLockableContainer(worldIn, pos);

            if (ilockablecontainer != null)
            {
            	ItemStack stack = Vars.locking ? playerIn.getHeldItem() : null;
            	if(stack != null && stack.getItem() == Items.key) {
            		if(ilockablecontainer.isLocked()) {
            			if(stack.hasDisplayName() && stack.getDisplayName().equals(ilockablecontainer.getLockCode().code())) {
            				ilockablecontainer.setLockCode(Passcode.EMPTY_CODE);
//                            playerIn.triggerAchievement(StatRegistry.chestUnlockedStat);
            				playerIn.connection.addHotbar(TextColor.BLUE + "%s wurde entriegelt", ilockablecontainer.getCommandName());
            				playerIn.connection.sendPacket(new SPacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F));
            				return true;
            			}
            		}
            		else if(stack.hasDisplayName()) {
            			ilockablecontainer.setLockCode(new Passcode(stack.getDisplayName()));
//                        playerIn.triggerAchievement(StatRegistry.chestLockedStat);
        				playerIn.connection.addHotbar(TextColor.ORANGE + "%s wurde verriegelt", ilockablecontainer.getCommandName());
        				playerIn.connection.sendPacket(new SPacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F));
            			return true;
	            	}
            	}
                playerIn.displayGUIChest(ilockablecontainer);

//                if (this.chestType == 0)
//                {
//                    playerIn.triggerAchievement(StatRegistry.chestOpenedStat);
//                }
//                else if (this.chestType == 1)
//                {
//                    playerIn.triggerAchievement(StatRegistry.trapChestStat);
//                }
            }

            return true;
        }
    }

    public ILockableContainer getLockableContainer(World worldIn, BlockPos pos)
    {
        TileEntity tileentity = worldIn.getTileEntity(pos);

        if (!(tileentity instanceof TileEntityChest))
        {
            return null;
        }
        else
        {
            ILockableContainer ilockablecontainer = (TileEntityChest)tileentity;

            if (this.isBlocked(worldIn, pos))
            {
                return null;
            }
            else
            {
                for (Facing enumfacing : Facing.Plane.HORIZONTAL)
                {
                    BlockPos blockpos = pos.offset(enumfacing);
                    Block block = worldIn.getState(blockpos).getBlock();

                    if (block == this)
                    {
                        if (this.isBlocked(worldIn, blockpos))
                        {
                            return null;
                        }

                        TileEntity tileentity1 = worldIn.getTileEntity(blockpos);

                        if (tileentity1 instanceof TileEntityChest)
                        {
                            if (enumfacing != Facing.WEST && enumfacing != Facing.NORTH)
                            {
                                ilockablecontainer = new InventoryLargeChest("Große Truhe", (TileEntityChest)ilockablecontainer, (TileEntityChest)tileentity1);
                            }
                            else
                            {
                                ilockablecontainer = new InventoryLargeChest("Große Truhe", (TileEntityChest)tileentity1, (TileEntityChest)ilockablecontainer);
                            }
                        }
                    }
                }

                return ilockablecontainer;
            }
        }
    }

    /**
     * Returns a new instance of a block's tile entity class. Called on placing the block.
     */
    public TileEntity createNewTileEntity(World worldIn)
    {
        return new TileEntityChest();
    }

    /**
     * Can this block provide power. Only wire currently seems to have this change based on its state.
     */
    public boolean canProvidePower()
    {
        return this.chestType == 1;
    }

    public int getWeakPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side)
    {
        if (!this.canProvidePower())
        {
            return 0;
        }
        else
        {
            int i = 0;
            TileEntity tileentity = worldIn.getTileEntity(pos);

            if (tileentity instanceof TileEntityChest)
            {
                i = ((TileEntityChest)tileentity).numPlayersUsing;
            }

            return ExtMath.clampi(i, 0, 15);
        }
    }

    public int getStrongPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side)
    {
        return side == Facing.UP ? this.getWeakPower(worldIn, pos, state, side) : 0;
    }

    private boolean isBlocked(World worldIn, BlockPos pos)
    {
        return this.isBelowSolidBlock(worldIn, pos) || this.isOcelotSittingOnChest(worldIn, pos);
    }

    private boolean isBelowSolidBlock(World worldIn, BlockPos pos)
    {
        return worldIn.getState(pos.up()).getBlock().isNormalCube();
    }

    private boolean isOcelotSittingOnChest(World worldIn, BlockPos pos)
    {
        for (Entity entity : worldIn.getEntitiesWithinAABB(EntityOcelot.class, new BoundingBox((double)pos.getX(), (double)(pos.getY() + 1), (double)pos.getZ(), (double)(pos.getX() + 1), (double)(pos.getY() + 2), (double)(pos.getZ() + 1))))
        {
            EntityOcelot entityocelot = (EntityOcelot)entity;

            if (entityocelot.isSitting())
            {
                return true;
            }
        }

        return false;
    }

    public boolean hasComparatorInputOverride()
    {
        return true;
    }

    public int getComparatorInputOverride(World worldIn, BlockPos pos)
    {
        return Container.calcRedstoneFromInventory(this.getLockableContainer(worldIn, pos));
    }

    /**
     * Convert the given metadata into a BlockState for this Block
     */
    public State getStateFromMeta(int meta)
    {
        Facing enumfacing = Facing.getFront(meta);

        if (enumfacing.getAxis() == Facing.Axis.Y)
        {
            enumfacing = Facing.NORTH;
        }

        return this.getState().withProperty(FACING, enumfacing);
    }

    /**
     * Convert the BlockState into the correct metadata value
     */
    public int getMetaFromState(State state)
    {
        return ((Facing)state.getValue(FACING)).getIndex();
    }

    protected Property[] getProperties()
    {
        return new Property[] {FACING};
    }
    
    public boolean isXrayVisible()
    {
        return true;
    }
	
	public String getFallbackTexture() {
		return "oak_planks";
	}
	
	protected Item getItemToRegister() {
		return new ItemChest(this);
	}
}
