// See mode_switch.h.

#include "core/view/mode_switch.h"

#include <cstddef>

namespace reasampler::view {

namespace {

// Left edge of segment i; segment i spans [edge(i), edge(i+1)). count assumed
// >= 1 by callers.
int segmentEdge(int x, int width, int i, int count) {
    return x + (i * width) / count;
}

} // namespace

std::vector<SegmentRect> computeSegmentRects(const HeaderRect& header,
                                             int segmentCount) {
    std::vector<SegmentRect> rects;
    if (segmentCount <= 0 || header.width <= 0) return rects;

    rects.reserve(static_cast<std::size_t>(segmentCount));
    for (int i = 0; i < segmentCount; ++i) {
        const int left = segmentEdge(header.x, header.width, i, segmentCount);
        const int right = segmentEdge(header.x, header.width, i + 1, segmentCount);
        SegmentRect r;
        r.x = left;
        r.y = header.y;
        r.width = right - left;
        r.height = header.height;
        rects.push_back(r);
    }
    return rects;
}

int hitTestSegment(int px, int py, const HeaderRect& header, int segmentCount) {
    if (segmentCount <= 0 || header.width <= 0 || header.height <= 0) return -1;

    if (px < header.x || px >= header.x + header.width ||
        py < header.y || py >= header.y + header.height)
        return -1;

    for (int i = 0; i < segmentCount; ++i) {
        const int left = segmentEdge(header.x, header.width, i, segmentCount);
        const int right = segmentEdge(header.x, header.width, i + 1, segmentCount);
        if (px >= left && px < right) return i;
    }
    return -1;
}

} // namespace reasampler::view
