--[[
Pumpkin farm thingy
- placemarks:
-- 'pf_home': above a coal chest
-- 'pf_start': start field
-- 'pf_dropoff': dropoff chest

On startup initialize by
- waiting for getting a gps fix
- determining orientation (move one block)
- going to 'home'

Reset:
- goto dropoff
- drop off stuff
- goto home
- refuel
- get a stack of saplings

Refuel:
- if fuel < threshold
- get roundup((fuel - threshold)/charcoal_value) charcoal
- refuel all
- [check for unknown items in inventory and dropoff and return]

TreeRun 
- move in a grid pattern
- dig down
- place down sapling
- when detecting a solid block in front
-- while block in front
--- dig
--- dig up
--- up
-- go back down to work level

Wait
- wait for 4 minutes or so

]]--

wait_time = 2*60 -- wait 4 minutes in between runs
fuel_threshold = 5120 -- fuel from a stack of coal
-- something is fucked up with the dimensions in tx grid_move
gx = 14
gy = 14

function reset_run()
    print('reset run, going to the dropoff point')
    tx.goto_placemark('pf_dropoff')
    print('dropping off excessive stuff')
    -- tx.dropOffDown, except={'pumpkin': 1}}
    turtle.select(1)
    turtle.dropDown(turtle.getItemCount(1)-1)
    for i=2,16 do
        turtle.select(i)
        turtle.dropDown(64)
    end
    tx.goto_placemark('pf_home')
    refuel()
    pumpkin_up()
end

function refuel()
    local remaining = turtle.getFuelLevel()
    turtle.select(1)
    while remaining < fuel_threshold do
        turtle.suckDown(1)
        turtle.refuel(64)
    end
    remaining = turtle.getFuelLevel()
    print('Got '..remaining..' fuel remaining now')
end

function pumpkin_up()
    local pumpkin_count = turtle.getItemCount(1)
    while pumpkin_count < 1 do
        turtle.select(1)
        if turtle.suckUp(1) then
            pumpkin_count = turtle.getItemCount(1)
        else
            print('I might not have enough pumpkin, continuing nonetheless')
            return false
        end
    end
    print('Got pumpkin(s) in slot 1 now')
end

function harvest_pumpkin()
    turtle.select(1)
    if turtle.compareDown(1) then
        turtle.digDown()
    end    
end

function tree_run()
    tx.goto_placemark('pf_start')
    tx.face('n')
    tx.grid_move{gx=gx, gy=gy, hook=harvest_pumpkin}   
end

function main()
    if tx.gps_init() then        
        reset_run()
        while true do
            tree_run()
            reset_run()
            os.sleep(wait_time)
        end
    else
        print('failed to init')
        return
    end
end

main()