Turtle = {}
require("movement")

function Turtle:new(t)
    t = t or {}
    setmetatable(t, self)
    self.__index = self
    return t
end

function Turtle:updateInv()
    self.inv = {}
    for slot = 1, 16 do
        self.inv[slot] = turtle.getItemDetail(slot, true)
    end
end

function Turtle:assertInvUpdate(update)
    if (update ~= false) then update = true end

    if self.inv == nil then
        update = true
    end

    assert(type(update) == "boolean","update must be of the type boolean")
    if update == true then
        self:updateInv()
    end
end

function Turtle:moveTo(target)
    target = self:resolveTarget(target)
    self:log("moving to target")

    moveTo(target[1], target[2], target[3], target[4], self.dir)

    self.x, self.y, self.z, self.dir = target[1], target[2], target[3], target[4]

    self:log("target reached")

end

function Turtle:offset(position, dir, offset)
    self:assertPositionFormat(position)
    assert(type(dir) == "number", "dir must be a number")
    assert(type(offset) == "number", "offset must be a number")
    local newPosition = self:copyPositionTable(position)
    dir = dir % 4
    if (dir == 0) then newPosition[1] = newPosition[1] - offset
    elseif (dir == 1) then newPosition[3] = newPosition[3] - offset
    elseif (dir == 2) then newPosition[1] = newPosition[1] + offset
    else newPosition[3] = newPosition[3] + offset
    end
    return newPosition
end

function Turtle:assertPositionFormat(position)
    assert(type(position) == "table", "the target is not a table")
    assert(type(position[1]) == "number" and type(position[2]) == "number" and type(position[3]) == "number", "the table doesn't contain the position")
    assert(type(position[4]) == "number", "direction is missing")
end

function Turtle:log(message)
    if self.verbose == true then
        print(message)
    end
end

function Turtle:copyPositionTable(position)
    self:assertPositionFormat(position)
    local positionClone = {}
    for i = 1, 4 do
        positionClone[i] = position[i]
    end
    return positionClone
end

function Turtle:reverseArray(a)
    local a2 = {}
    assert(type(a) == "table", "argument must be an array")
    for i = 1, #a do
        a2[#a -i + 1] = a[i]
    end
    return a2
end