package common.block.tech;

import common.block.Block;
import common.block.BlockContainer;
import common.block.Rotatable;
import common.block.Material;
import common.entity.npc.EntityNPC;
import common.entity.types.EntityLiving;
import common.init.Blocks;
import common.init.Items;
import common.inventory.Container;
import common.inventory.InventoryHelper;
import common.item.Item;
import common.item.ItemStack;
import common.model.Model;
import common.model.ModelProvider;
import common.model.ModelRotation;
import common.model.ParticleType;
import common.properties.Property;
import common.rng.Random;
import common.tileentity.TileEntity;
import common.tileentity.TileEntityFurnace;
import common.util.BlockPos;
import common.util.Facing;
import common.world.AWorldClient;
import common.world.State;
import common.world.World;
import common.world.AWorldServer;

public class BlockFurnace extends BlockContainer implements Rotatable
{
    private final boolean isBurning;
    private static boolean keepInventory;

    public BlockFurnace(boolean isBurning)
    {
        super(Material.SOLID);
        this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH));
        this.isBurning = isBurning;
    }

    /**
     * Get the Item that this Block should drop when harvested.
     */
    public Item getItemDropped(State state, Random rand, int fortune)
    {
        return Items.furnace;
    }

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

    private void setDefaultFacing(World worldIn, BlockPos pos, State state)
    {
        if (!worldIn.client)
        {
            Block block = worldIn.getState(pos.north()).getBlock();
            Block block1 = worldIn.getState(pos.south()).getBlock();
            Block block2 = worldIn.getState(pos.west()).getBlock();
            Block block3 = worldIn.getState(pos.east()).getBlock();
            Facing enumfacing = (Facing)state.getValue(FACING);

            if (enumfacing == Facing.NORTH && block.isFullBlock() && !block1.isFullBlock())
            {
                enumfacing = Facing.SOUTH;
            }
            else if (enumfacing == Facing.SOUTH && block1.isFullBlock() && !block.isFullBlock())
            {
                enumfacing = Facing.NORTH;
            }
            else if (enumfacing == Facing.WEST && block2.isFullBlock() && !block3.isFullBlock())
            {
                enumfacing = Facing.EAST;
            }
            else if (enumfacing == Facing.EAST && block3.isFullBlock() && !block2.isFullBlock())
            {
                enumfacing = Facing.WEST;
            }

            worldIn.setState(pos, state.withProperty(FACING, enumfacing), 2);
        }
    }

    
    public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand)
    {
        if (this.isBurning)
        {
            Facing enumfacing = (Facing)state.getValue(FACING);
            double d0 = (double)pos.getX() + 0.5D;
            double d1 = (double)pos.getY() + rand.doublev() * 6.0D / 16.0D;
            double d2 = (double)pos.getZ() + 0.5D;
            double d3 = 0.52D;
            double d4 = rand.doublev() * 0.6D - 0.3D;

            switch (enumfacing)
            {
                case WEST:
                    worldIn.spawnParticle(ParticleType.SMOKE_NORMAL, d0 - d3, d1, d2 + d4, 0.0D, 0.0D, 0.0D);
                    worldIn.spawnParticle(ParticleType.FLAME, d0 - d3, d1, d2 + d4, 0.0D, 0.0D, 0.0D);
                    break;

                case EAST:
                    worldIn.spawnParticle(ParticleType.SMOKE_NORMAL, d0 + d3, d1, d2 + d4, 0.0D, 0.0D, 0.0D);
                    worldIn.spawnParticle(ParticleType.FLAME, d0 + d3, d1, d2 + d4, 0.0D, 0.0D, 0.0D);
                    break;

                case NORTH:
                    worldIn.spawnParticle(ParticleType.SMOKE_NORMAL, d0 + d4, d1, d2 - d3, 0.0D, 0.0D, 0.0D);
                    worldIn.spawnParticle(ParticleType.FLAME, d0 + d4, d1, d2 - d3, 0.0D, 0.0D, 0.0D);
                    break;

                case SOUTH:
                    worldIn.spawnParticle(ParticleType.SMOKE_NORMAL, d0 + d4, d1, d2 + d3, 0.0D, 0.0D, 0.0D);
                    worldIn.spawnParticle(ParticleType.FLAME, d0 + d4, d1, d2 + d3, 0.0D, 0.0D, 0.0D);
            }
        }
    }

    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 TileEntityFurnace)
            {
                playerIn.displayGUIChest((TileEntityFurnace)tileentity);
//                playerIn.triggerAchievement(StatRegistry.furnaceStat);
            }

            return true;
        }
    }

    public static void setState(boolean active, World worldIn, BlockPos pos)
    {
        State iblockstate = worldIn.getState(pos);
        TileEntity tileentity = worldIn.getTileEntity(pos);
        keepInventory = true;

        if (active)
        {
            worldIn.setState(pos, Blocks.lit_furnace.getState().withProperty(FACING, iblockstate.getValue(FACING)), 3);
            worldIn.setState(pos, Blocks.lit_furnace.getState().withProperty(FACING, iblockstate.getValue(FACING)), 3);
        }
        else
        {
            worldIn.setState(pos, Blocks.furnace.getState().withProperty(FACING, iblockstate.getValue(FACING)), 3);
            worldIn.setState(pos, Blocks.furnace.getState().withProperty(FACING, iblockstate.getValue(FACING)), 3);
        }

        keepInventory = false;

        if (tileentity != null)
        {
            tileentity.validate();
            worldIn.setTileEntity(pos, tileentity);
        }
    }

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

    /**
     * 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().getOpposite());
    }

    /**
     * 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, placer.getHorizontalFacing().getOpposite()), 2);

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

            if (tileentity instanceof TileEntityFurnace)
            {
                ((TileEntityFurnace)tileentity).setCustomInventoryName(stack.getDisplayName());
            }
        }
    }

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

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

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

    public boolean hasComparatorInputOverride()
    {
        return true;
    }

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

    public Item getItem(World worldIn, BlockPos pos)
    {
        return Items.furnace;
    }

    /**
     * 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)
    {
        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 Model getModel(ModelProvider provider, String name, State state) {
    	return provider.getModel("furnace_side").add().du("furnace_top").n("furnace_front_" + (this.isBurning ? "on" : "off"))
    			.s().we().rotate(ModelRotation.getNorthRot(state.getValue(FACING)));
    }
}
