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

local sides = peripheral.getNames()
mininglasers = {}
for _, side in pairs(sides) do
  if peripheral.getType(side) == "warpdriveMiningLaser" then
    print("Wrapping " .. side)
    table.insert(mininglasers, peripheral.wrap(side))
  end
end


local noExit = true
layerOffset = 1
onlyOres = false
silktouch = false
local args = {...}
if #args > 0 then
  if args[1] == "help" or args[1] == "?" then
    print("Usage: mine <layerOffset> <onlyOres> <silktouch>")
    print()
    print("Miner always mines below it, down to bedrock.")
    print("Set layerOffset to define starting level.")
    print("Power consumption will be much lower in space.")
    print("Mining only ores is faster but more expensive...")
    print("Mining laser can't go through forcefields.")
    print("Mined chests will drop their contents.")
    print()
    noExit = false
  else
    layerOffset = tonumber( args[1] ) or 1
  end
  
  if #args > 1 then
    if args[2] == "true" or args[2] == "1" then
      onlyOres = true
    end
  end
  
  if #args > 2 then
    if args[3] == "true" or args[3] == "1" then
      silktouch = true
    end
  end
end

if #mininglasers == 0 then
  term.setBackgroundColor(colors.red)
  term.setTextColor(colors.white)
  term.write("No mining laser detected")

  noExit = false
end
if noExit then
  for _, mininglaser in pairs(mininglasers) do
    local _, isActive = mininglaser.state()
    if not isActive then
      mininglaser.offset(layerOffset)
      mininglaser.onlyOres(onlyOres)
      mininglaser.silktouch(silktouch)
      
      mininglaser.start()
    end
  end
  os.sleep(1)
end

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

term.setTextColor(colors.blue)
if noExit then
  local areActive
  repeat
    areActive = false
    for key,mininglaser in pairs(mininglasers) do
      local status, isActive, energy, currentLayer, mined, total = mininglaser.state()
      
      term.setBackgroundColor(colors.black)
      term.clear()
      term.setBackgroundColor(colors.lime)
      term.setCursorPos(1, 1)
      term.write(label .. " - Mining laser " .. key .. " of " .. #mininglasers)
      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("Mined " .. mined .. " out of " .. total .. " blocks at layer " .. currentLayer .. "   ")
      
      if isActive then
        areActive = true
        os.sleep(1)
      else
        os.sleep(0.1)
      end
    end
  until not areActive
end

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

print()
print("Program closed")
