--- Fieldwork course for vines

---@class FieldworkCourseVine: CourseGenerator.FieldworkCourse
local FieldworkCourseVine = CpObject(CourseGenerator.FieldworkCourse)

--- Generate rows for the vine course. We use the VineScanner to generate the lines, and then use them directly as the
--- rows. This assumes that the lines generated by the VineScanner all point in the same direction.
--- If the tool works on both side of the row, like spraying the vines on both sides, we must move the rows by half the
--- working width in between the lines.
---@param workingWidth number
---@param lines table "lines" generated by the VineScanner
---@param rowsBetweenLines boolean if true, rows will be generated between the lines, otherwise on the lines
---@return CourseGenerator.Row[] Rows generated from the lines
function FieldworkCourseVine.generateRows(workingWidth, lines, rowsBetweenLines)
    local rows = {}
    for _, l in ipairs(lines) do
        local row = CourseGenerator.Row(workingWidth, { { x = l.x1, y = -l.z1 }, { x = l.x2, y = -l.z2 } })
        -- extend a bit to make sure it intersects the boundary
        row:extendStart(20)
        row:extendEnd(20)
        table.insert(rows, row)
    end
    if rowsBetweenLines then
        local offset
        if (rows[2] and rows[1][1]:getExitEdge():isPointOnLeft(rows[2][1])) then
            -- the second row is on the left side of the first, so move all rows to the left
            offset = workingWidth / 2
        else
            -- the second row is on the right side of the first, so move all rows to the right
            offset = - workingWidth / 2
        end
        -- remove the last one, to keep only the ones between the lines
        table.remove(rows)
        for i = 1, #rows do
            -- move each row to in between the lines
            rows[i] = rows[i]:createNext(offset)
        end
    end
    return rows
end

function FieldworkCourseVine:init(context, rows)
    self.logger = Logger('FieldworkCourseVine')
    self:_setContext(context)
    self.headlandPath = Polyline()

    self.circledIslands = {}
    self:setupAndSortIslands()

    self.center = CourseGenerator.CenterPredefinedRows(self.context, self.boundary, nil, self.context.startLocation, self.bigIslands, rows)
    self.center:generate()
end

---@class CourseGenerator.FieldworkCourseVine : CourseGenerator.FieldworkCourse
CourseGenerator.FieldworkCourseVine = FieldworkCourseVine
