--[[
Tree farm thingy
- placemarks:
-- 'home': above a coal chest
-- 'sapling': sapling chest
-- '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

]]--

max_try = 20
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 = 6

function init() 
    print('trying to initialize')
    local x, y, z = gps.locate(30)
    -- local x, y, z = coords
    if x == nil then
        print("Couldn't get GPS location, returning nil")
        return false
    end
    
    print("I am at ",x," ",y," ",z)
    -- Now to determine my orientation
    while tx.detect() do
        tx.right()
    end
    -- should set the move mode to push in tx, but that's not yet implemented
    local moved = false
    print('moving one block to get my orientation')
    for j=1,max_try do
        if turtle.forward() then
            moved = true
            break
        else
            print('obstructing, trying again')
            os.sleep(1)
        end
    end
    if not moved then
        print('Failed to determine direction, returning nil')
        return false
    end
    local nx, ny, nz = gps.locate(30)
    print('I moved to '..nx..', '..ny..', '..nz)
    --local nx, ny, nz = ncoords
    -- move back, using turtle, cause back isn't implemented in tx
    moved = false
    for j=1,max_try do
        if turtle.back() then
            moved = true
            break
        else
            print('obstructing while moving back, trying again')
            os.sleep(1)
        end
    end
    -- go calculate heading
    if nx ~= x then
        print('x changed')
        if nx > x then 
            print('x increased')
            orientation = 'e'
        else
            print('x decreased')
            orientation = 'w'
        end
    else
        print('z must have changed')
        if nz > z then
            print('z increased')
            orientation = 's'
        else
            print('z decreased')
            orientation = 'n'
        end
    end
    print('I am facing '..orientation)
    tx.init{x=x, y=y, z=z, o=orientation, move_mode='dig'}
    tx.save_state()
    return true
end

function reset_run()
    print('reset run, going to the dropoff point')
    tx.goto_placemark('dropoff')
    print('dropping off excessive stuff')
    local wood = tx.getItemCount(2)
    if wood > 1 then
        tx.select(2)
        tx.dropDown(wood-1)
    end
    for i=3,16 do
        turtle.select(i)
        turtle.dropDown(64)
    end
    tx.goto_placemark('home')
    refuel()
    sapling_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 sapling_up()
    local sapling_count = turtle.getItemCount(1)
    while sapling_count < 64 do
        turtle.select(1)
        if turtle.suckUp(64 - sapling_count) then
            sapling_count = turtle.getItemCount(1)
        else
            print('I might not have enough saplings, continuing nonetheless')
            return false
        end
    end
    print('Got 64 saplings in slot 1 now')
end

function plant_sapling()
    tx.select(1)
    tx.placeDown()
    tx.suckDown()
end

function fell_tree()
    tx.select(2)
    if tx.compare() then
        print('detected tree, harvesting up')
        tx.placemark('bottom')
        tx.select(2)
        while tx.compare() do
            tx.dig()
            tx.select(1)
            if not tx.up() then break end
            tx.select(2)
        end
        print('going back down')
        tx.goto_placemark('bottom')
        tx.select(1)
        tx.down()
        tx.dig()
        tx.place()
        tx.up()
        tx.placeDown()
    else
        -- nothing to do
        return
    end
end

function tree_run()
    tx.goto_placemark('start')
    tx.grid_move{gx=gx, gy=gy, hook=plant_sapling, prefw_hook=fell_tree}   
end

function main()
    if 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()