local args = { ... }

package.path = package.path .. ";" .. "lib/?"

-- local turtle = require "turtlePlaceholder"
local utils = require "utils"

local turnedLeft = nil
if args[1] == "rightturn" or args[1] == "leftturn" then
  turnedLeft = (args[1] == "rightturn")
else
  print("usage: \"makefloor [leftturn|rightturn]\" whatever the first turn may be")
  return
end

local pre = "A room with walls atleast 2 high and robot should start in a corner"
local post = "a room with a floor of $material"

if not utils.confirmExecution(pre, post) then
  return
end

local curContainer = 1
turtle.select(curContainer)

local function selectMatStack()
  itemCount = turtle.getItemCount(curContainer)
  while itemCount == 0 do
    if curContainer == 9 then
      return false
    end
    curContainer = curContainer + 1
    turtle.select(curContainer)
    itemCount = turtle.getItemCount(curContainer)
  end
  return true
end

local function checkIfNextTurn()
  if turnedLeft then turnAction = turtle.turnRight else turnAction = turtle.turnLeft end
  turnAction()
  retval = not turtle.detect()
  if not turnedLeft then turnAction = turtle.turnRight else turnAction = turtle.turnLeft end
  turnAction()
  return retval
end

local function fillblock()
  shouldTurn = turtle.detect()
  if shouldTurn then
    couldTurn = checkIfNextTurn()
  end

  if not selectMatStack() then
    return false
  end
  turtle.placeDown()
  if shouldTurn then
    if turnedLeft then turnAction = turtle.turnRight else turnAction = turtle.turnLeft end
    turnAction()
    turtle.forward()
    turnAction()
    turnedLeft = not turnedLeft
  else
    turtle.forward()
  end
  return true
end

while not detectDown() do
  turtle.down()
end

turtle.up()

while fillblock() do end