import requests

from urllib.parse import urlsplit
from urllib.parse import urlunsplit
from urllib.parse import urlencode
from urllib.parse import parse_qs


class CursorPagination:
    def __init__(self, cursor):
        self.cursor = cursor

    def _get_next_cursor(self, response):
        return response.json().get(self.cursor)

    def get_active_cursor(self, request):
        return request.params.get(self.cursor, '')

    def get_next_request(self, response, request):
        if not response:
            return request

        cursor = self._get_next_cursor(
            response
        )
        if not cursor:
            return None

        split = urlsplit(response.url)
        original_params = parse_qs(split.query)
        # Update original_params with new cursor
        original_params.update(
            {
                self.cursor: cursor
            }
        )
        new_url = urlunsplit((
            split.scheme,
            split.netloc,
            split.path,
            urlencode(original_params),
            None,
        ))
        # Now, instead of using a new requests.Request object
        # we return the one that was passed with an update
        # only on the new_url
        request.url = new_url
        return request


class ShopifyCursorPagination(CursorPagination):
    cursor = 'page_info'

    def _get_next_cursor(self, response):
        headers = response.headers
        if not headers:
            return None
        values = headers.get("Link", headers.get("link"))
        if not values:
            return None
        result = {}
        for value in values.split(", "):
            link, rel = value.split("; ")
            result[rel.split('"')[1]] = link[1:-1]
        return result.get("next")
