if not term.isColor() then
  print("Advanced computer required")
  exit()
end

sides = peripheral.getNames()
treefarms = {}
for key,side in pairs(sides) do
  if peripheral.getType(side) == "warpdriveLaserTreeFarm" then
    print("Wrapping " .. side)
    table.insert(treefarms, peripheral.wrap(side))
  end
end


noExit = true
breakLeaves = true
tapTrees = true
silktouch = false
args = {...}
if #args > 0 then
  if args[1] == "help" or args[1] == "?" then
    print("Usage: farm <breakLeaves> <tapTrees> <silktouch>")
    print()
    print("Farmer always farm above it.")
    print("Use 'true' or '1' to enable an option.")
    print("Use 'false' or '0' to disable an option.")
    print("Default is to break leaves and tap rubber trees.")
    print("Sapplings will be automatically replanted.")
    print("Farming automatically stops when inventory is full.")
    print()
    noExit = false
  else
    if args[1] == "false" or args[1] == "0" then
      breakLeaves = false
    end
  end
  
  if #args > 1 then
    if args[2] == "false" or args[2] == "0" then
      tapTrees = false
    end
  end
  
  if #args > 2 then
    if args[3] == "true" or args[3] == "1" then
      silktouch = true
    end
  end
end

if #treefarms == 0 then
  term.setBackgroundColor(colors.red)
  term.setTextColor(colors.white)
  term.write("No laser tree farm detected")
  
  noExit = false
end
if noExit then
  for key,treefarm in pairs(treefarms) do
    statusString, isActive = treefarm.state()
    if not isActive then
      treefarm.breakLeaves(breakLeaves)
      treefarm.tapTrees(tapTrees)
      treefarm.silktouch(silktouch)
      
      treefarm.start()
    end
  end
  sleep(1)
end

label = os.getComputerLabel()
if label then
else
  label = "" .. os.getComputerID()
end

term.setTextColor(colors.blue)
if noExit then
  repeat
    isActive = false
    for key,treefarm in pairs(treefarms) do
      status, isActive, energy, totalHarvested, currentValuable, totalValuables = treefarm.state()
      
      term.setBackgroundColor(colors.black)
      term.clear()
      term.setBackgroundColor(colors.lime)
      term.setCursorPos(1, 1)
      term.write(label .. " - Laser tree farm " .. key .. " of " .. #treefarms)
      term.setBackgroundColor(colors.black)
      term.setCursorPos(1, 3)
      term.write("Status: " .. status .. "   ")
      term.setBackgroundColor(colors.black)
      term.setCursorPos(1, 5)
      term.write("Energy level is " .. energy .. " EU")
      term.setCursorPos(1, 7)
      term.write("Farmed " .. currentValuable .. " out of " .. totalValuables .. " blocks in current cycle    ")
      term.setCursorPos(1, 9)
      term.write("Harvested " .. totalHarvested .. " items and counting...   ")
      
      if isActive then
        sleep(1)
      else
        sleep(0.1)
      end
    end
  until not isActive
end

term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
print()
