# Path: gbdxtools/rda/error.py
# class NotFound(Exception):
#     pass
# 
# class BadRequest(Exception):
#     pass


import os
import json
import time
from gbdxtools.rda.error import NotFound, BadRequest
from urllib.parse import urlencode
from functools import lru_cache

VIRTUAL_RDA_URL = os.environ.get("VIRTUAL_RDA_URL", "https://rda.geobigdata.io/v1")


@lru_cache()
def req_with_retries(conn, url, retries=5):
    for i in range(retries):
        try:
            res = conn.get(url)
            if res.status_code not in [502, 429]:
                return res
            elif res.status_code == 501:
                raise Exception('501 Auth error')
        except:
            pass
        time.sleep(0.5 * (i + 1))
    raise Exception('RDA is overloaded')


def get_template_stats(conn, template_id, **kwargs):
    qs = urlencode(kwargs)
    url = "{}/template/{}/display_stats.json?{}".format(VIRTUAL_RDA_URL, template_id, qs)
    req = req_with_retries(conn, url)
    if req.status_code == 200:
        return req.json()

# Path: gbdxtools/rda/error.py
# class NotFound(Exception):
#     pass
# 
# class BadRequest(Exception):
#     pass


# Path: gbdxtools/rda/graph.py
import os
import json
import time
from gbdxtools.rda.error import NotFound, BadRequest
from urllib.parse import urlencode
from functools import lru_cache


VIRTUAL_RDA_URL = os.environ.get("VIRTUAL_RDA_URL", "https://rda.geobigdata.io/v1")


@lru_cache()
def req_with_retries(conn, url, retries=5):
    for i in range(retries):
        try:
            res = conn.get(url)
            if res.status_code not in [502, 429]:
                return res
            elif res.status_code == 501:
                raise Exception('501 Auth error')
        except:
            pass
        time.sleep(0.5 * (i + 1))
    raise Exception('RDA is overloaded')


def get_template_stats(conn, template_id, **kwargs):
    qs = urlencode(kwargs)
    url = "{}/template/{}/display_stats.json?{}".format(VIRTUAL_RDA_URL, template_id, qs)
    req = req_with_retries(conn, url)
    if req.status_code == 200:
        return req.json()

    else: