starttime = os.epoch("local")

function printf(data)
    print(textutils.serialize(data))
end

function step()
    turtle.digUp()
    turtle.up()
    turtle.dig()
    turtle.turnRight()
    turtle.dig()
    turtle.turnRight()
    turtle.dig()
    turtle.turnRight()
    turtle.dig()
    turtle.turnRight()
end

function chop()
    turtle.dig()
    turtle.forward()
    while turtle.detectUp() do
        step()
    end
end

function descend()
    while not turtle.detectDown() do
    turtle.down()
    end
end

function takeItemOutOfChestSlot(chestSlot,turtleSlot,chestDir)
    local SLOT_TURTLE_EMPTY_CHEST = 16
    local chest = peripheral.wrap(chestDir)
    turtle.select(SLOT_TURTLE_EMPTY_CHEST)
    turtle.placeUp()
    sleep(.2)
    local topchest = peripheral.wrap("top");
    chest.pushItems(peripheral.getName(topchest),chestSlot)
    turtle.select(turtleSlot)
    turtle.suckUp()
    turtle.select(SLOT_TURTLE_EMPTY_CHEST)
    turtle.digUp()
    turtle.select(turtleSlot)
end

function dumpItems()
    turtle.turnLeft();turtle.turnLeft()
    for i=1,15 do
        turtle.select(i)
        turtle.drop()
    end
    turtle.turnLeft();turtle.turnLeft()
end

function replant()
    local chestDir = "back"
    local chest = peripheral.wrap(chestDir)
    local itemlist = chest.list()
    local saplingIndex = 0
    for _ in pairs(itemlist) do
        print(textutils.serialise(_))
        if itemlist[_].name == "minecraft:oak_sapling" then
            saplingIndex = _
        end
    end
    if saplingIndex > 0 then
        -- peripheral.call(chest, "pullitems", )
        printf(saplingIndex)
        takeItemOutOfChestSlot(saplingIndex,15,"back")
    end
    turtle.select(15)
    turtle.place()
    turtle.turnLeft();turtle.turnLeft()
    turtle.drop()
    turtle.turnLeft();turtle.turnLeft()
    turtle.select(1)
    -- peripheral.getMethods()
end

function chestTest(chestSlot)
    local chest = peripheral.wrap("back");
    turtle.select(17)
    turtle.placeUp()
    local topchest = peripheral.wrap("top");
    chest.pushItems(peripheral.getName(topchest),chestSlot)
end

function waitForTree()
    while true do
        turtle.suck()
        has_block, data = turtle.inspect()
        if has_block then
            if(data) then
                if data.tags["minecraft:mineable/axe"] == true then
                    print((os.epoch("local")-starttime)/1000,"choppable")
                    if(data.name ~= "minecraft:oak_sapling") then
                        chop()
                        descend()
                        turtle.back()
                        dumpItems()
                        replant()
                    end
                    print(data.name)
                else
                    print((os.epoch("local")-starttime)/1000,"not choppable")
                end
            end
        end
        sleep(1)
    end
end

waitForTree()