package common.block;

import common.dispenser.BehaviorDefaultDispenseItem;
import common.dispenser.IBehaviorDispenseItem;
import common.dispenser.IBlockSource;
import common.dispenser.IPosition;
import common.dispenser.PositionImpl;
import common.entity.npc.EntityNPC;
import common.entity.types.EntityLiving;
import common.init.DispenserRegistry;
import common.init.RegistryDefaulted;
import common.inventory.Container;
import common.inventory.InventoryHelper;
import common.item.CheatTab;
import common.item.Item;
import common.item.ItemStack;
import common.material.Material;
import common.model.Model;
import common.model.ModelProvider;
import common.model.ModelRotation;
import common.properties.IProperty;
import common.properties.PropertyBool;
import common.properties.PropertyDirection;
import common.rng.Random;
import common.tileentity.TileEntity;
import common.tileentity.TileEntityDispenser;
import common.util.BlockPos;
import common.util.Facing;
import common.world.State;
import common.world.World;
import common.world.AWorldServer;

public class BlockDispenser extends BlockContainer
{
    public static final PropertyDirection FACING = PropertyDirection.create("facing");
    public static final PropertyBool TRIGGERED = PropertyBool.create("triggered");
    public static final RegistryDefaulted<Item, IBehaviorDispenseItem> dispenseBehaviorRegistry = new RegistryDefaulted(new BehaviorDefaultDispenseItem());
    protected Random rand = new Random();

    public BlockDispenser()
    {
        super(Material.rock);
        this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(TRIGGERED, Boolean.valueOf(false)));
        this.setTab(CheatTab.tabTech);
    }

    /**
     * How many world ticks before ticking
     */
    public int tickRate(World worldIn, BlockPos pos)
    {
        return 4;
    }

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

    private void setDefaultDirection(World worldIn, BlockPos pos, State state)
    {
        if (!worldIn.client)
        {
            Facing enumfacing = (Facing)state.getValue(FACING);
            boolean flag = worldIn.getState(pos.north()).getBlock().isFullBlock();
            boolean flag1 = worldIn.getState(pos.south()).getBlock().isFullBlock();

            if (enumfacing == Facing.NORTH && flag && !flag1)
            {
                enumfacing = Facing.SOUTH;
            }
            else if (enumfacing == Facing.SOUTH && flag1 && !flag)
            {
                enumfacing = Facing.NORTH;
            }
            else
            {
                boolean flag2 = worldIn.getState(pos.west()).getBlock().isFullBlock();
                boolean flag3 = worldIn.getState(pos.east()).getBlock().isFullBlock();

                if (enumfacing == Facing.WEST && flag2 && !flag3)
                {
                    enumfacing = Facing.EAST;
                }
                else if (enumfacing == Facing.EAST && flag3 && !flag2)
                {
                    enumfacing = Facing.WEST;
                }
            }

            worldIn.setState(pos, state.withProperty(FACING, enumfacing).withProperty(TRIGGERED, Boolean.valueOf(false)), 2);
        }
    }

    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
        {
            TileEntity tileentity = worldIn.getTileEntity(pos);

            if (tileentity instanceof TileEntityDispenser)
            {
                playerIn.displayGUIChest((TileEntityDispenser)tileentity);

//                if (tileentity instanceof TileEntityDropper)
//                {
//                    playerIn.triggerAchievement(StatRegistry.dropperStat);
//                }
//                else
//                {
//                    playerIn.triggerAchievement(StatRegistry.dispenserStat);
//                }
            }

            return true;
        }
    }

    protected void dispense(World worldIn, BlockPos pos)
    {
        BlockSourceImpl blocksourceimpl = new BlockSourceImpl(worldIn, pos);
        TileEntityDispenser tileentitydispenser = (TileEntityDispenser)blocksourceimpl.getBlockTileEntity();

        if (tileentitydispenser != null)
        {
            int i = tileentitydispenser.getDispenseSlot();

            if (i < 0)
            {
                worldIn.playAuxSFX(1001, pos, 0);
            }
            else
            {
                ItemStack itemstack = tileentitydispenser.getStackInSlot(i);
                IBehaviorDispenseItem ibehaviordispenseitem = this.getBehavior(itemstack);

                if (ibehaviordispenseitem != IBehaviorDispenseItem.itemDispenseBehaviorProvider)
                {
                    ItemStack itemstack1 = ibehaviordispenseitem.dispense(blocksourceimpl, itemstack);
                    tileentitydispenser.setInventorySlotContents(i, itemstack1.stackSize <= 0 ? null : itemstack1);
                }
            }
        }
    }

    protected IBehaviorDispenseItem getBehavior(ItemStack stack)
    {
        return (IBehaviorDispenseItem)DispenserRegistry.REGISTRY.getObject(stack == null ? null : stack.getItem());
    }

    /**
     * Called when a neighboring block changes.
     */
    public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock)
    {
        boolean flag = worldIn.isBlockPowered(pos) || worldIn.isBlockPowered(pos.up());
        boolean flag1 = ((Boolean)state.getValue(TRIGGERED)).booleanValue();

        if (flag && !flag1)
        {
            worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn, pos));
            worldIn.setState(pos, state.withProperty(TRIGGERED, Boolean.valueOf(true)), 4);
        }
        else if (!flag && flag1)
        {
            worldIn.setState(pos, state.withProperty(TRIGGERED, Boolean.valueOf(false)), 4);
        }
    }

    public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand)
    {
//        if (!worldIn.client)
//        {
        this.dispense(worldIn, pos);
//        }
    }

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

    /**
     * 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, int meta, EntityLiving placer)
    {
        return this.getState().withProperty(FACING, BlockPistonBase.getFacingFromEntity(worldIn, pos, placer)).withProperty(TRIGGERED, Boolean.valueOf(false));
    }

    /**
     * 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)
    {
        worldIn.setState(pos, state.withProperty(FACING, BlockPistonBase.getFacingFromEntity(worldIn, pos, placer)), 2);

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

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

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

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

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

    /**
     * Get the position where the dispenser at the given Coordinates should dispense to.
     */
    public static IPosition getDispensePosition(IBlockSource coords)
    {
        Facing enumfacing = getFacing(coords.getBlockMetadata());
        double d0 = coords.getX() + 0.7D * (double)enumfacing.getFrontOffsetX();
        double d1 = coords.getY() + 0.7D * (double)enumfacing.getFrontOffsetY();
        double d2 = coords.getZ() + 0.7D * (double)enumfacing.getFrontOffsetZ();
        return new PositionImpl(d0, d1, d2);
    }

    /**
     * Get the facing of a dispenser with the given metadata
     */
    public static Facing getFacing(int meta)
    {
        return Facing.getFront(meta & 7);
    }

    public boolean hasComparatorInputOverride()
    {
        return true;
    }

    public int getComparatorInputOverride(World worldIn, BlockPos pos)
    {
        return Container.calcRedstone(worldIn.getTileEntity(pos));
    }

    /**
     * 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 3;
    }

    /**
     * Possibly modify the given BlockState before rendering it on an Entity (Minecarts, Endermen, ...)
     */
    public State getStateForEntityRender(State state)
    {
        return this.getState().withProperty(FACING, Facing.SOUTH);
    }

    /**
     * Convert the given metadata into a BlockState for this Block
     */
    public State getStateFromMeta(int meta)
    {
        return this.getState().withProperty(FACING, getFacing(meta)).withProperty(TRIGGERED, Boolean.valueOf((meta & 8) > 0));
    }

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

        if (((Boolean)state.getValue(TRIGGERED)).booleanValue())
        {
            i |= 8;
        }

        return i;
    }

    protected IProperty[] getProperties()
    {
        return new IProperty[] {FACING, TRIGGERED};
    }
    
    public boolean isMagnetic() {
    	return true;
    }

    public Model getModel(ModelProvider provider, String name, State state) {
    	if(state.getValue(FACING) == Facing.DOWN || state.getValue(FACING) == Facing.UP)
    		return provider.getModel("furnace_top").add().dnswe().u(name + "_front_vertical")
    				.rotate(state.getValue(FACING) == Facing.DOWN ? ModelRotation.X180_Y0 : ModelRotation.X0_Y0);
    	else
    		return provider.getModel(name + "_front_horizontal").add().du("furnace_top").n()
    				.s("furnace_side").we("furnace_side").rotate(ModelRotation.getNorthRot(state.getValue(FACING)));
    }

    public IProperty<?>[] getIgnoredProperties() {
    	return new IProperty[] {TRIGGERED};
    }
}
