## Script (Python) "getBatch"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=results, size=9, orphan=2, overlap=0
##title=Get current batch from results sequence
##

# got this script here:
# http://www.zopelabs.com/cookbook/1015785843
# Thanks to Casey Duncan

from ZTUtils import Batch

request = context.REQUEST
model = request.model

record_id = model.id + '_batch'
batch_record = request.get(record_id, None)

try:
    if batch_record is None:
        start = 0
    else:
        start = int(batch_record.get('start', 0))
        size = int(batch_record.get('size', size))
except ValueError:
    start = 0

batch = Batch(results, size, start, 0, orphan, overlap)

def getBatchLink(qs, new_start):
    if new_start is not None:
        if not qs:
            qs = '%s.start:record=%d' % (record_id, new_start)
        elif qs.startswith('%s.start:record=' % record_id):
            qs = qs.replace(
                '%s.start:record=%s' % (record_id, start),
                '%s.start:record=%d' % (record_id, new_start))
        elif qs.find('&%s.start:record=' % record_id) != -1:
            qs = qs.replace(
                '&%s.start:record=%s' % (record_id, start),
                '&%s.start:record=%d' % (record_id, new_start))
        else:
            qs = '%s&%s.start:record=%d' % (qs, record_id, new_start)
        return qs

# create a new query string with the correct batch_start/end 
# for the next/previous batch
nr_of_results = len(results)
if batch.end < nr_of_results:
    qs = getBatchLink(request.QUERY_STRING, batch.end)
    request.set(
        '%s.next_batch_url' % record_id, '%s?%s' % (request.URL, qs))
    if (batch.end + batch.size + batch.orphan) >= nr_of_results:
        next = nr_of_results - batch.end
    else:
        next = batch.size
    request.set('%s.next_amount' % record_id, next)

if start > 0:
    new_start = start - size
    if new_start < 0: new_start = 0
    qs = getBatchLink(request.QUERY_STRING, new_start)
    request.set(
        '%s.previous_batch_url' % record_id, '%s?%s' % (request.URL, qs))
    
return batch
