import("extensions.math", "local")
local gui = require("gui")

local start_angle = -math.pi / 2.0;
local skip_detents = 3;
local num_detents = 5;
local period = 5.0;

local stroke_head_tween = function(t)
    t = math.sawtooth(t, num_detents);
    return math.interval(0.0, 0.5, t);
end

local stroke_tail_tween = function(t)
    t = math.sawtooth(t, num_detents);
    return math.interval(0.5, 1.0, t);
end

local step_tween = function(t)
    return math.floor(math.lerp(0.0, num_detents, t));
end

return function(x, y, radius, thickness, color)
    local t = (clock() % period) / period;
    local head_value = stroke_head_tween(t);
    local tail_value = stroke_tail_tween(t);
    local step_value = step_tween(t);
    local rotation_value = math.sawtooth(t, num_detents);
    local min_arc =  30.0 / 360.0 * 2.0 * math.pi;
    local max_arc = 270.0 / 360.0 * 2.0 * math.pi;
    local step_offset = skip_detents * 2.0 * math.pi / num_detents;
    local rotation_compensation = (4.0*math.pi - step_offset - max_arc)%(2*math.pi);
    local a_min = start_angle + tail_value * max_arc + rotation_value * rotation_compensation - step_value * step_offset;
    local a_max = a_min + (head_value - tail_value) * max_arc + min_arc;
    local num_segments = 32;
    gui.stroke(color)
    gui.stroke_weight(thickness)
    for i = 0, num_segments-1 do
        local a1 = a_min + (i / (num_segments)) * (a_max - a_min);
        local a2 = a_min + ((i + 1) / (num_segments)) * (a_max - a_min);
        gui.line(x + math.cos(a1) * radius, y + math.sin(a1) * radius, x + math.cos(a2) * radius, y + math.sin(a2) * radius);
    end
end