-- Robot producteur de ressource botania

-- Function deplacement + refuel
function deplace()
	info("Deplacement "..turtle.getFuelLevel())
	if turtle.getFuelLevel()==0 then
		turtle.select(16)
    turtle.refuel(1)
	end
	turtle.forward() 
end

function verif()
	ok, donne = turtle.inspectDown()
  if ok then
    if donne.name=="Botania:livingrock" then
      return false
    elseif donne.name=="Botania:livingwood" then
      return false
    else
      return true
    end
  else
  	perma=false
    return false
  end
end
function stop()
  ok, donne = turtle.inspectDown()
  if ok==false then
  	return true
  else
 	 return false
  end
end
function change()
	info("Attente")
	while verif() do
		os.sleep(3)
	end
 
	info("Minage / placement")
	turtle.select(2)
	turtle.digDown()
	turtle.select(1)
	turtle.placeDown()
end

function info(text)
	term.clear()
	term.setCursorPos(1,1)
	print(text)
end

local perma=true
function go()
	local pos=0
	local coin=0	
	while perma do
		change()   	
		deplace()  
		pos=pos+1
    if pos==2 then      
			if coin==3 then
      	info("Depart")
        turtle.turnLeft()
        turtle.select(2)
				turtle.drop()
        
         if stop() then
          return
          info("Fin")
        end
        
        turtle.turnRight()
       	charge()
        info("Charge charbon")
				if turtle.getItemCount(16) == 0 then
					turtle.select(16)
					turtle.suckUp()
				end		
        
        turtle.turnRight()
				coin=0
			else
				turtle.turnRight()	
        coin=coin+1
			end
			pos=0
			
		end	
	end
end
function charge()
	info("Charge obj")
	if turtle.getItemCount(1) < 8 then
		turtle.select(1)
		turtle.suck()
    qte=turtle.getItemCount(1)
    if qte<8 then
    	turtle.drop()
    end
    if turtle.getItemCount(2) ~= 0 then
   		turtle.select(2)
      turtle.drop()
    end
	end
end
function premier()
	info("Depos ressource vide")
	local pos=0
	local coin=0	
  local perma2=true
  turtle.select(1)
	while perma2 do		
		turtle.placeDown()
		deplace()    
		pos=pos+1
    if pos==2 then      
			if coin==3 then
      	turtle.turnRight()
        perma2=false
        return
			else
				turtle.turnRight()	
        coin=coin+1
			end
			pos=0
			
		end	
	end
end

info("Placement");
ok=0
while ok<2 do
	turtle.turnLeft()
  presence, donne = turtle.inspect()
  if presence then
  	ok=0
  else
  	ok=ok+1
  end
end

turtle.turnLeft()
charge()
turtle.turnRight()

ok, donne = turtle.inspectDown()
if ok then
	go()
else
	if turtle.getItemCount(1) == 0 then
  	info("Pas de ressource")
  else
		premier()
  	go()
  end	
end