import json
import time
import hashlib
import hmac
import logging
from .. import config


class Request(object):
    @classmethod
    def send(cls, session, endpoint, post=None):
        log = logging.getLogger('main')

        try:
            if post is not None:  # POST
                response = session.post(
                    config.API_URL + endpoint, data=cls.generate_signature(post))
            else:  # GET
                response = session.get(config.API_URL + endpoint)
            if response.status_code == 200:
                log.debug("Request OK! Response: " + response.text)
                return json.loads(response.text)
            else:
                try:
                    s = json.loads(response.text)
                except:
                    s = ""
                log.error("Request return " +
                          str(response.status_code) + " error: " + str(response))
                if response.status_code == 429:
                    sleep_minutes = 5
                    log.warning(
                        "That means 'too many requests'. I'll go to sleep for %d minutes." % sleep_minutes)
                    time.sleep(sleep_minutes * 60)
                return None
        except Exception as e:
            log.error("Request error: " + str(e))
            return None

    @staticmethod
    def generate_signature(data):
        return 'ig_sig_key_version=' + config.SIG_KEY_VERSION + '&signed_body=' + hmac.new(
            config.IG_SIG_KEY.encode('utf-8'), data.encode('utf-8'), hashlib.sha256).hexdigest() + '.' + data

@@ -751,42 +751,358 @@
     
-except:%0A                    s = %22%22
+    if s%5B'message'%5D == 'checkpoint_required':%0A                        warn = s%5B'message'%5D%0A                        if 'checkpoint_url' in s:%0A                            warn += %22 %22 + s%5B'checkpoint_url'%5D%0A                        log.warning(warn)%0A                        return None%0A                except:%0A                    error = str(response.text)
 %0A   
@@ -1215,21 +1215,13 @@
 %22 + 
-str(response)
+error
 )%0A  

add checkpoint_required error handling