import random


def mutation_single_customer_rerouting(vehicle, p1, quality, duration,
                                       setup_time, setup_cost, demand):
    """Re-routing involves randomly selecting one customer, and removing that
    customer from the existing route. The customer is then inserted in the
    best feasible insertion location within the entire chromosome.
    """
    route = random.randint(0, len(p1.routes[vehicle]) - 1)
    if len(p1.routes[vehicle][route]) < 1:
        return p1
    removal_index = random.randint(0, len(p1.routes[vehicle][route]) - 1)
    node = p1.routes[vehicle][route][removal_index]

    p_res = p1.clone()
    # remove customer from chromosome
    p_res.remove_node(vehicle, route, removal_index, quality[vehicle],
                      duration, setup_time, demand[vehicle],
                      setup_cost[vehicle])

    # insert customer at best insert location
    if p_res.insertion_minimal_cost(node, quality, duration, setup_time,
                                    demand, setup_cost):
        return p_res
    return p1