'Calculates the disease_stats_aggregate for a specific parameter at a
specific location over the range of dates.
@param location_id: location to aggregate at
@param children: locations to aggregate from
@param parameter_id: arameter to aggregate
@param dates: dates to aggregate for (as JSON string)'

@staticmethod
def disease_stats_update_location_aggregates(location_id, children, parameter_id, dates):

    db = current.db
    atable = current.s3db.disease_stats_aggregate
    ifield = atable.id
    lfield = atable.location_id
    pfield = atable.parameter_id
    dfield = atable.date
    children = json.loads(children)
    query = (((pfield == parameter_id) & (atable.deleted != True)) & lfield.belongs(children))
    rows = db(query).select(atable.sum, dfield, lfield, orderby=(lfield, (~ dfield)))
    if (not rows):
        return
    query = ((lfield == location_id) & (pfield == parameter_id))
    existing = db(query).select(ifield, dfield)
    exists = {}
    for e in existing:
        exists[e.date] = e.id
    from dateutil.parser import parse
    dates = json.loads(dates)
    insert = atable.insert
    for date in dates:
        date = parse(date)
        date = date.date()
        last_location = None
        values = []
        vappend = values.append
        for row in rows:
            if (date < row.date):
                continue
            new_location_id = row.location_id
            if (new_location_id != last_location):
                last_location = new_location_id
                vappend(row.sum)
        if values:
            values_sum = sum(values)
        else:
            values_sum = 0
        attr = dict(agg_type=2, sum=values_sum)
        if (date in exists):
            db((ifield == exists[date])).update(**attr)
        else:
            insert(parameter_id=parameter_id, location_id=location_id, date=date, **attr)
