package common.block.foliage;

import common.block.Block;
import common.block.Rotatable;
import common.block.Material;
import common.block.SoundType;
import common.color.Colorizer;
import common.entity.npc.EntityNPC;
import common.entity.types.EntityLiving;
import common.init.Blocks;
import common.init.Items;
import common.item.Item;
import common.item.ItemStack;
import common.item.block.ItemDoublePlant;
import common.item.tool.ItemShears;
import common.model.Model;
import common.model.ModelProvider;
import common.properties.Property;
import common.properties.PropertyEnum;
import common.rng.Random;
import common.tileentity.TileEntity;
import common.util.BlockPos;
import common.util.Facing;
import common.util.Identifyable;
import common.util.Facing.Axis;
import common.vars.Vars;
import common.world.IWorldAccess;
import common.world.State;
import common.world.World;
import common.world.AWorldServer;

public class BlockDoublePlant extends BlockBush implements Rotatable, IGrowable
{
    public static final PropertyEnum<BlockDoublePlant.EnumBlockHalf> HALF = PropertyEnum.<BlockDoublePlant.EnumBlockHalf>create("half", BlockDoublePlant.EnumBlockHalf.class);
	public static final BlockDoublePlant[] PLANTS = new BlockDoublePlant[EnumPlantType.values().length];

    private final EnumPlantType type;
    
    public static BlockDoublePlant getByType(EnumPlantType type) {
    	return PLANTS[type.ordinal()];
    }

    public BlockDoublePlant(EnumPlantType type)
    {
        super(Material.BUSH);
        this.type = type;
        this.setDefaultState(this.getBaseState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.LOWER).withProperty(FACING, Facing.NORTH));
        this.setHardness(0.0F);
        this.setStepSound(SoundType.GRASS);
        this.setFlammable(60, 100);
        PLANTS[type.ordinal()] = this;
    }
    
    public EnumPlantType getType() {
    	return this.type;
    }

    public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand)
    {
        if(Vars.plantDry && worldIn.getTemperatureC(pos) >= 50.0f)
        {
        	boolean upper = state.getValue(HALF) == EnumBlockHalf.UPPER;
        	if(!upper)
        		pos = pos.up();
        	if(upper || worldIn.getState(pos).getBlock() == this)
	        	worldIn.setState(pos, Blocks.air.getState());
        	pos = pos.down();
        	if(!upper || worldIn.getState(pos).getBlock() == this)
	        	worldIn.setState(pos, this.type == EnumPlantType.GRASS || worldIn.rand.chance(20) ? Blocks.air.getState() : 
	        			Blocks.dead_bush.getState());
        	return;
        }
        super.updateTick(worldIn, pos, state, rand);
    }

    public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos)
    {
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
    }

    public boolean canPlaceBlockAt(World worldIn, BlockPos pos)
    {
        return super.canPlaceBlockAt(worldIn, pos) && worldIn.isAirBlock(pos.up());
    }

    /**
     * Whether this Block can be replaced directly by other blocks (true for e.g. tall grass)
     */
    public boolean isReplaceable(World worldIn, BlockPos pos)
    {
        State iblockstate = worldIn.getState(pos);

        if (iblockstate.getBlock() != this)
        {
            return true;
        }
        else
        {
            return this.type == BlockDoublePlant.EnumPlantType.FERN || this.type == BlockDoublePlant.EnumPlantType.GRASS;
        }
    }

    protected void checkAndDropBlock(World worldIn, BlockPos pos, State state)
    {
        if (!this.canBlockStay(worldIn, pos, state))
        {
            boolean flag = state.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER;
            BlockPos blockpos = flag ? pos : pos.up();
            BlockPos blockpos1 = flag ? pos.down() : pos;
            Block block = (Block)(flag ? this : worldIn.getState(blockpos).getBlock());
            Block block1 = (Block)(flag ? worldIn.getState(blockpos1).getBlock() : this);

            if (block == this)
            {
                worldIn.setState(blockpos, Blocks.air.getState(), 2);
            }

            if (block1 == this)
            {
                worldIn.setState(blockpos1, Blocks.air.getState(), 3);

                if (!flag)
                {
                    this.dropBlockAsItem(worldIn, blockpos1, state, 0);
                }
            }
        }
    }

    public boolean canBlockStay(World worldIn, BlockPos pos, State state)
    {
        if (state.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER)
        {
            return worldIn.getState(pos.down()).getBlock() == this;
        }
        else
        {
            State iblockstate = worldIn.getState(pos.up());
            return iblockstate.getBlock() == this && super.canBlockStay(worldIn, pos, iblockstate);
        }
    }

    /**
     * Get the Item that this Block should drop when harvested.
     */
    public Item getItemDropped(State state, Random rand, int fortune)
    {
        if (state.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER)
        {
            return null;
        }
        else
        {
            return this.type == BlockDoublePlant.EnumPlantType.FERN ? null : (this.type == BlockDoublePlant.EnumPlantType.GRASS ? (rand.chance(8) ? Items.wheat : null) : this.getItem());
        }
    }

    public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass)
    {
        return this.type != BlockDoublePlant.EnumPlantType.GRASS && this.type != BlockDoublePlant.EnumPlantType.FERN ? 16777215 : Colorizer.getGrassColor(worldIn, pos);
    }

    public void placeAt(World worldIn, BlockPos lowerPos, int flags)
    {
        worldIn.setState(lowerPos, this.getState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.LOWER), flags);
        worldIn.setState(lowerPos.up(), this.getState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.UPPER), flags);
    }

    /**
     * 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.up(), this.getState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.UPPER), 2);
    }

    public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te)
    {
        if (worldIn.client || player.getCurrentEquippedItem() == null || !(player.getCurrentEquippedItem().getItem() instanceof ItemShears) || state.getValue(HALF) != BlockDoublePlant.EnumBlockHalf.LOWER || !this.onHarvest(worldIn, pos, state, player))
        {
            super.harvestBlock(worldIn, player, pos, state, te);
        }
    }

    public void onBlockHarvested(World worldIn, BlockPos pos, State state, EntityNPC player)
    {
        if (state.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER)
        {
            if (worldIn.getState(pos.down()).getBlock() == this)
            {
//                if (!player.creative)
//                {
                State iblockstate = worldIn.getState(pos.down());

                if (this.type != BlockDoublePlant.EnumPlantType.FERN && this.type != BlockDoublePlant.EnumPlantType.GRASS)
                {
                    worldIn.destroyBlock(pos.down(), true);
                }
                else if (!worldIn.client)
                {
                    if (player.getCurrentEquippedItem() != null && player.getCurrentEquippedItem().getItem() instanceof ItemShears)
                    {
                        this.onHarvest(worldIn, pos, iblockstate, player);
                        worldIn.setBlockToAir(pos.down());
                    }
                    else
                    {
                        worldIn.destroyBlock(pos.down(), true);
                    }
                }
                else
                {
                    worldIn.setBlockToAir(pos.down());
                }
//                }
//                else
//                {
//                    worldIn.setBlockToAir(pos.down());
//                }
            }
        }
//        else if (player.creative && worldIn.getState(pos.up()).getBlock() == this)
//        {
//            worldIn.setState(pos.up(), Blocks.air.getState(), 2);
//        }

        super.onBlockHarvested(worldIn, pos, state, player);
    }

    private boolean onHarvest(World worldIn, BlockPos pos, State state, EntityNPC player)
    {
        if (this.type != BlockDoublePlant.EnumPlantType.FERN && this.type != BlockDoublePlant.EnumPlantType.GRASS)
        {
            return false;
        }
        else
        {
            spawnAsEntity(worldIn, pos, new ItemStack(this.type == BlockDoublePlant.EnumPlantType.GRASS ? Items.tallgrass : Items.fern, 2));
            return true;
        }
    }

    /**
     * Whether this IGrowable can grow
     */
    public boolean canGrow(World worldIn, BlockPos pos, State state, boolean isClient)
    {
        return this.type != BlockDoublePlant.EnumPlantType.GRASS && this.type != BlockDoublePlant.EnumPlantType.FERN;
    }

    public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, State state)
    {
        return true;
    }

    public void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state)
    {
        spawnAsEntity(worldIn, pos, new ItemStack(this.getItem()));
    }

    /**
     * Convert the given metadata into a BlockState for this Block
     */
    public State getStateFromMeta(int meta)
    {
        return (meta & 8) > 0 ? this.getState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.UPPER) : this.getState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.LOWER);
    }

    /**
     * Convert the BlockState into the correct metadata value
     */
    public int getMetaFromState(State state)
    {
        return state.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER ? 8 | ((Facing)state.getValue(FACING)).getHorizontalIndex() : 0;
    }

    protected Property[] getProperties()
    {
        return new Property[] {HALF, FACING};
    }

    public Model getModel(ModelProvider provider, String name, State state) {
    	if(this.type == EnumPlantType.SUNFLOWER && state.getValue(HALF) == EnumBlockHalf.UPPER)
    		return provider.getModel("sunflower_front")
    				.add(0.8f, 0f, 8f, 15.2f, 8f, 8f).noShade().rotate(8, 8, 8, Axis.Y, 45, true).ns("sunflower_top")
    				.uv(0, 8, 16, 16).noCull()
					.add(8f, 0f, 0.8f, 8f, 8f, 15.2f).noShade().rotate(8, 8, 8, Axis.Y, 45, true).we("sunflower_top")
					.uv(0, 8, 16, 16).noCull()
					.add(9.6f, -1f, 1f, 9.6f, 15f, 15f).noShade().rotate(8, 8, 8, Axis.Z, 22.5f, true).w("sunflower_back")
					.uv(0, 0, 16, 16).noCull().e().uv(0, 0, 16, 16).noCull();
    	else if(this.type == EnumPlantType.FERN || this.type == EnumPlantType.GRASS)
    		return provider.getModel(this.type.getName() + "_" + (state.getValue(HALF) == EnumBlockHalf.UPPER 
    				? "top" : "bottom")).crossTint();
    	else
    		return provider.getModel(this.type.getName() + "_" + (state.getValue(HALF) == EnumBlockHalf.UPPER 
			? "top" : "bottom")).cross();
    }

    public Property<?>[] getIgnoredProperties() {
    	return new Property[] {FACING};
    }
	
	protected Item getItemToRegister() {
		return new ItemDoublePlant(this);
	}

    public static enum EnumBlockHalf implements Identifyable
    {
        UPPER,
        LOWER;

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

        public String getName()
        {
            return this == UPPER ? "upper" : "lower";
        }
    }

    public static enum EnumPlantType implements Identifyable
    {
        SUNFLOWER(0, "sunflower", "Sonnenblume"),
        SYRINGA(1, "syringa", "Flieder"),
        GRASS(2, "large_tallgrass", "Hohes Gras"),
        FERN(3, "large_fern", "Großer Farn"),
        ROSE(4, "rose_bush", "Rosenstrauch"),
        PAEONIA(5, "paeonia", "Pfingstrose");

        private static final BlockDoublePlant.EnumPlantType[] META_LOOKUP = new BlockDoublePlant.EnumPlantType[values().length];
        private final int meta;
        private final String name;
        private final String display;

//        private EnumPlantType(int meta, String name)
//        {
//            this(meta, name, name);
//        }

        private EnumPlantType(int meta, String name, String display)
        {
            this.meta = meta;
            this.name = name;
            this.display = display;
        }

        public int getMeta()
        {
            return this.meta;
        }

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

        public static BlockDoublePlant.EnumPlantType byMetadata(int meta)
        {
            if (meta < 0 || meta >= META_LOOKUP.length)
            {
                meta = 0;
            }

            return META_LOOKUP[meta];
        }

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

        public String getDisplay()
        {
            return this.display;
        }

        static {
            for (BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype : values())
            {
                META_LOOKUP[blockdoubleplant$enumplanttype.getMeta()] = blockdoubleplant$enumplanttype;
            }
        }
    }
}
