package com.commit451.gitlab.util;

import android.net.Uri;

import retrofit.Response;
import timber.log.Timber;

public final class PaginationUtil {

    private static final String NEXT_PAGE_SUFFIX = "rel=\"next\"";
    private static final String FIRST_PAGE_SUFFIX = "rel=\"first\"";
    private static final String LAST_PAGE_SUFFIX = "rel=\"last\"";

    private PaginationUtil() {}

    public static PaginationData parse(Response response) {
        Uri next = null;
        Uri first = null;
        Uri last = null;

        String header = response.headers().get("Link");
        if (header != null) {
            String[] parts = header.split(",");
            for (String part : parts) {
                try {
                    int linkStart = part.indexOf('<') + 1;
                    int linkEnd = part.indexOf('>');

                    Uri link = Uri.parse(part.substring(linkStart, linkEnd));

                    if (part.contains(NEXT_PAGE_SUFFIX)) {
                        next = link;
                    } else if (part.contains(FIRST_PAGE_SUFFIX)) {
                        first = link;
                    } else if (part.contains(LAST_PAGE_SUFFIX)) {
                        last = link;
                    }
                } catch (Exception e) {
                    Timber.e(e, "An error occurred");
                }
            }
        }

        return new PaginationData(next, first, last);
    }

    public static class PaginationData {
        private final Uri next;
        private final Uri first;
        private final Uri last;

        private PaginationData(Uri next, Uri first, Uri last) {
            this.next = next;
            this.first = first;
            this.last = last;
        }

        public Uri getNext() {
            return next;
        }

        public Uri getFirst() {
            return first;
        }

        public Uri getLast() {
            return last;
        }
    }
}

@@ -144,16 +144,83 @@
 Util %7B%0A%0A
+    private static final String PREV_PAGE_SUFFIX = %22rel=%5C%22prev%5C%22%22;%0A
     priv
@@ -504,24 +504,49 @@
 response) %7B%0A
+        Uri prev = null;%0A
         Uri 
@@ -1017,24 +1017,127 @@
          if 
+(part.contains(PREV_PAGE_SUFFIX)) %7B%0A                        prev = link;%0A                    %7D else if 
 (part.contai
@@ -1598,16 +1598,22 @@
 ionData(
+prev, 
 next, fi
@@ -1672,16 +1672,48 @@
 nData %7B%0A
+        private final Uri prev;%0A
         
@@ -1833,24 +1833,34 @@
 ionData(Uri 
+prev, Uri 
 next, Uri fi
@@ -1872,24 +1872,54 @@
 Uri last) %7B%0A
+            this.prev = prev;%0A
             
@@ -2001,32 +2001,99 @@
 ast;%0A        %7D%0A%0A
+        public Uri getPrev() %7B%0A            return prev;%0A        %7D%0A%0A
         public U

Add previous link to PaginationData