module Paginate
  include Common;

  def parse(document)
    output={ 'next' => 'false' };
    limit=ENV['PAGE_LIMIT'].to_i;
    total=document['total_rows'];
    offset=document['offset'];
    length=0;
    if document['rows']
      length=document['rows'].length;
      if length > 0 && length > limit
        if offset+limit < total
          first=document['rows'][0];
          last=document['rows'].pop();
          output['next_docid']=last['id'];
          output['next_startkey']=compact(last['key']);
          output['previous_docid']=first['id'];
          output['previous_startkey']=compact(first['key']);
          output['next']='true';
        end
      end
    end
    output['total']=total;
    output['offset']=offset;
    output['length']=length;
    output['limit']=limit;
    output['document']=document;
    return output;
  end

  def exports(output)
    format="export page_%s='%s';";
    lines=[];
    output.each_pair do |k,v|
      if k == "document"
        next;
      end
      lines.push(sprintf(format,k,v));
    end
    return lines;
  end

  def write(output)
    tmpfile=ENV['PAGE_TMP_FILE'];
    lines=exports(output);
    File.open(tmpfile, 'w') { |file|
      file.write(lines.join("\n") + "\n");
    }
    return Common::stringify(output['document']);
  end
end
