--[[
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 = 9
gy = 9

function reset_run()
    tx.mode = 'push'
    print('reset run, going to the dropoff point')
    tx.goto_placemark('pf_dropoff')
    print('dropping off excessive stuff')
    for i=1,16 do
        turtle.select(i)
        turtle.drop(64)
    end
    refuel()
end

function refuel()
    local remaining = turtle.getFuelLevel()
    if remaining < fuel_threshold then
        tx.goto_placemark('pf_refuel')
        print('Got '..remaining..' fuel remaining, I need to refuel')
        while remaining < fuel_threshold do
            turtle.suck()
            turtle.refuel(64)
            remaining = turtle.getFuelLevel()
        end        
        print('Got '..remaining..' fuel remaining now')
    else
        print('Got '..remaining..' fuel remaining, no need to refuel')
    end
end

function harvest_pumpkin()
    local odd = (tx.state.x + tx.state.z) % 2
    --print('Odd = '..odd)
    if odd ~= 1 then
        print('Must dig...')
        turtle.digDown()
    else
        print('Skipping...')
    end
end

function pumpkin_run()
    turtle.select(1)
    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
            pumpkin_run()
            reset_run()
            --os.sleep(wait_time)
        end
    else
        print('failed to init')
        return
    end
end

main()