'''
Created on Jun 18, 2020

@author Saurabh Kumar Pandey
'''
import pycurl
import StringIO 
import urllib
import config as cfg

headers = [""]

class curllib:
    global error
    
    def __init__(self): 
        global check
        
    def header_function(self, header_line, **kwargs):
        headers[0] += header_line  
        

    def request(self, data, **kwargs):
        try:
            self.curlurl = data['url']
            self.pycurl_conn_timeout = data.get('conn_timeout') or 30
            self.pycurl_processing_timeout = data.get('processing_timeout') or 30            
            post_fields = data.get('postfields')
            if post_fields != None:
                self.post_fields = urllib.urlencode(post_fields)          
            try:
                storage = StringIO.StringIO() 
                c = pycurl.Curl() 
                c.setopt(pycurl.URL, self.curlurl)
                c.setopt(pycurl.CONNECTTIMEOUT, self.pycurl_conn_timeout)
                c.setopt(pycurl.TIMEOUT, self.pycurl_processing_timeout)
                #c.setopt(c.PROXY, cfg.aadhaar['proxy'])
                c.setopt(c.WRITEFUNCTION, storage.write)
                c.setopt(pycurl.SSL_VERIFYPEER, 0)
                c.setopt(pycurl.HEADERFUNCTION, self.header_function)
                c.setopt(pycurl.SSL_VERIFYHOST, 0)        
                c.setopt(pycurl.POST, 1)
                c.setopt(pycurl.POSTFIELDS, self.post_fields)
               
                try:
                    c.perform()
                except pycurl.error as err:
                    return {'status':'error', 'resp':err}    
                
                content_response =  storage.getvalue()
                respHeader = headers[0].split(' ') # as the curl error code is in same line splitted by '<space character>'
                repHeader = respHeader[1]
                return {'status':'success', 'header_code':repHeader, 'response':content_response}
                        
            except Exception as curlexception:
                response_code = 999
                return {'status':'Failed', 'header_code':response_code, 'excpn': curlexception}
        except Exception as libexception:
            response_code = 9999
            return {'status':'Failed', 'header_code':response_code, 'excpn': libexception}