package de.craften.plugins.educraft.luaapi.functions;

import de.craften.plugins.educraft.environment.LivingArmorStandBehavior;
import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Material;
import org.bukkit.TreeSpecies;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.material.Tree;
import org.luaj.vm2.Varargs;

/**
 * A function to fell an entire tree at once.
 */
public class FellTreeFunction extends EduCraftApiFunction {
    @Override
    protected void beforeExecute(Varargs varargs) {
        LivingArmorStandBehavior armorStand = (LivingArmorStandBehavior) getApi().getEntity().getBehaviors(LivingArmorStandBehavior.class).iterator().next();
        armorStand.setItemInHand(new ItemStack(Material.DIAMOND_AXE));
    }

    @Override
    public Varargs execute(Varargs varargs) {
        Block block = getApi().getBlockAhead();
        MaterialData data = block.getState().getData();
        if (data instanceof Tree) {
            getApi().getInventory().giveItem(block.getType(), fellTree(block, ((Tree) data).getSpecies()));
        }
        return NIL;
    }

    @Override
    protected void afterExecute(Varargs varargs) {
        LivingArmorStandBehavior armorStand = (LivingArmorStandBehavior) getApi().getEntity().getBehaviors(LivingArmorStandBehavior.class).iterator().next();
        armorStand.setItemInHand(null);
    }

    private int fellTree(Block block, TreeSpecies species) {
        int count = 1;
        block.breakNaturally();

        for (BlockFace face : BlockFace.values()) {
            if (face != BlockFace.DOWN) {
                Block neighbor = block.getRelative(face);
                BlockState state = neighbor.getState();
                if (state instanceof Tree && ((Tree) state).getSpecies().equals(species)) {
                    count += fellTree(neighbor, species);
                }
            }
        }
        return count;
    }
}

@@ -1008,24 +1008,112 @@
 ockAhead();%0A
+        if (block.getType() == Material.LOG %7C%7C block.getType() == Material.LOG_2) %7B%0A    
         Mate
@@ -1160,24 +1160,28 @@
 ();%0A        
+    
 if (data ins
@@ -1192,24 +1192,28 @@
 eof Tree) %7B%0A
+    
             
@@ -1304,24 +1304,38 @@
 pecies()));%0A
+            %7D%0A
         %7D%0A  
@@ -1714,10 +1714,125 @@
 t = 
-1;
+0;%0A        if (block.getType() == Material.LOG %7C%7C block.getType() == Material.LOG_2) %7B%0A            count++;%0A        %7D
 %0A   

Fix wood log count and only fell trees when starting at a wood log.