#include "weightedload"

unsigned Weightedload::target(struct in_addr clientip,
			   BackendVector &targetlist) {
    // First loop thru and add up the weights.
    double total_load = 0;
    for (unsigned i = 0; i < targetlist.size(); i++) {
	if (balancer.backend(targetlist[i]).loadavg() == 0)
	    total_load += 1 / 0.01;
	else
	    total_load += 1 / balancer.backend(targetlist[i]).loadavg();
    }

    // Now pick a random number from 0 to total_load
    // 4294967295 = 2^32 - 1
    double pick_load = total_load * mt_rand() * (1.0 / 4294967295.0);

    msg ("Weighted by Load Average; load-range is " << total_load <<
	 ", and the selected load-range is " << pick_load << '\n');

    // Now see which server that means!
    total_load = 0;
    for (unsigned i = 0; i < targetlist.size(); i++) {
	if (balancer.backend(targetlist[i]).loadavg() == 0)
	    total_load += 1 / 0.01;
	else
	    total_load += 1 / balancer.backend(targetlist[i]).loadavg();
	if (total_load >= pick_load) {
// 	    if (config.verbose()) {
// 		ostringstream o;
// 		o << balancer.backend(targetlist[i]).loadavg();
// 		msg ("Weighted by Load Average chose backend " +
// 		 (string)balancer.backend(i).description() + " which has a " +
// 		 "load average of " + o.str() + "\n");
// 	    }
	    return targetlist[i];
	}
    }


    throw Error("Weighted-load algorithm: no available back ends ");
    return targetlist[0]; // We need some kind of default...
}
