import requests
from requests.exceptions import HTTPError
from robot.api import logger as robotlogger


def apirequest(method, uri, api_headers, query_params, body, *_args):

    """
    *_args is an optional parameter.
    values can be provided for this parameter when document to be uploaded.
    """
    api_uri = uri
    robotlogger.info("Request Type: %s" % method)
    robotlogger.info("api_uri: %s" % api_uri)
    robotlogger.info("Request headers: %s" % api_headers)
    robotlogger.info("query_params: %s" % query_params)
    robotlogger.info("Request body: %s" % body)
    file=None

    if len(_args)>0:
        file=_args[0]

    try:
        if method == 'get' or method == 'GET':
            response = requests.get(api_uri, headers=api_headers, params=query_params, timeout=120)
        elif method == 'post' or method == 'POST':
            response = requests.post(api_uri, headers=api_headers, params=query_params, data=body, files=file, timeout=120)
        elif method == 'put' or method == 'PUT':
            response = requests.put(api_uri, headers=api_headers, params=query_params, data=body, timeout=120)
        elif method == 'delete' or method == 'DELETE':
            response = requests.delete(api_uri, headers=api_headers)
        elif method == 'patch' or method == 'PATCH':
            response = requests.patch(api_uri, headers=api_headers, params=query_params, data=body, timeout=120)
        else:
            robotlogger.error("Invalid parameters for API request")
            error = 'Invalid Parameters'
            return error
    except HTTPError as http_err:
        response = {http_err}
        robotlogger.error(response)
        return response
    except Exception as err:
        response = {err}
        robotlogger.error(response)
        return response
    except TimeoutError as timeout_err:
        response = {timeout_err}
        robotlogger.error(response)
        return response
    except requests.exceptions.Timeout as req_timeout:
        robotlogger.error('API request failed with timeout error, 120 seconds')
        robotlogger.error(req_timeout)
        raise req_timeout
    else:
        if len(response.text) < 100:
            robotlogger.info(response.text)
        return response
