import Statistics
using Random


include("typedefs.jl")


function get_centroid(neighbourhood, id)::Node
    xdev = 40
    ydev = 40
    mean_x = Statistics.mean([node.cx for node in neighbourhood]) + rand(-xdev:xdev)
    mean_y = Statistics.mean([node.cx for node in neighbourhood]) + rand(-ydev:ydev)
    distances = [hypot(mean_x-node.cx, mean_y-node.cy) for node in neighbourhood]
    return Node(id, "provider", mean_x, mean_y)
end


function clusterise(nodelist::Vector{Node}, k::Int)::Vector{Node}
    return random_radius_clustering(nodelist, k)
end


function random_radius_clustering(nodelist::Vector{Node}, k::Int)::Vector{Node}
    n = length(nodelist)
    m = n - k
    min_r = 5
    max_r = 30
    centroids = []
    last_id = maximum(x -> x.id, nodelist)
    closed_set = copy(nodelist)
    for i in range(1, stop=m)
        open_set = copy(nodelist)
        random_point = open_set[rand(1:m)]
        distances = [hypot(random_point.cx-node.cx, random_point.cy-node.cy) for node in open_set]
        neighbours = []
        eligible_nodes = [node for (i, node) in enumerate(open_set) if distances[i] >= min_r && distances[i] <= max_r]
        eligible_distances = [distances[i] for (i, node) in enumerate(open_set) if distances[i] >= min_r && distances[i] <= max_r]
        # for j in range(1, stop=k)
        #     min_dist_ind = argmin(eligible_distances)
        #     min_dist_node = popat!(eligible_nodes, min_dist_ind)
        #     push!(neighbours, min_dist_node)
        # end
        push!(centroids, get_centroid(eligible_nodes, last_id))
        last_id += 1
    end
    
    append!(closed_set, centroids)
    return closed_set
end
