from urllib3.util import parse_url
from urllib.parse import urljoin, parse_qs

from django.conf import settings
import requests


class PoizonClient:
    SPU_GET_DATA_ENDPOINT = 'spu_get_data'

    MAX_RETRIES = 2

    def __init__(self, token: str):
        self.api_url = 'http://124.222.99.75/'
        self.token = token
        self.session = requests.Session()

    def request(self, method, url, *args, **kwargs):
        params = kwargs.pop('params', {})
        params.update({"token": self.token})

        joined_url = urljoin(self.api_url, url)
        request = requests.Request(method, joined_url, params=params, *args, **kwargs)

        retries = 0
        while retries < self.MAX_RETRIES:
            retries += 1
            prepared = self.session.prepare_request(request)
            r = self.session.send(prepared, timeout=settings.EXTERNAL_API_TIMEOUT_SEC)

            # TODO: handle/log errors
            return r

    @staticmethod
    def get_spu_id(url):
        try:
            # Go to short dw4.co url to get the full one from redirect
            if 'dw4.co' in url:
                r = requests.get(url)
                url = r.url

            url = parse_url(url)
            qs = parse_qs(url.query)
            spu_id = qs.get('spuId')
            return spu_id.pop(0) if spu_id else None
        except Exception as exc:
            # TODO: handle/log errors
            return None

    def get_good_info(self, spu_id):
        params = {'spuId': str(spu_id)}
        return self.request('GET', self.SPU_GET_DATA_ENDPOINT, params=params)
