
import requests
from gravitee_cli.gravitee.config import Gravitee_configuration
from gravitee_cli.exeptions import GraviteeRequestError
from requests import RequestException

APIS_CONTEXT = "/management/apis/"

class gravitee_api:
    def __init__(self, conf=None, debug=False):
        self.config = Gravitee_configuration()
        self.timeout = 1

    def get_apis(self):
        return self._request("GET")

    def get_api(self, id):
        return self._request("GET", "{}".format(id))

    def start_api(self, id):
        return self._request("POST", "{}?action=START".format(id))

    def stop_api(self, id):
        return self._request("POST", "{}?action=STOP".format(id))

    def state_api(self, id):
        return self._request("GET", "{}/state".format(id))
    
    def deploy_api(self, id):
        return self._request("GET", "{}/deploy".format(id))
    
    def _request(self, verbe, path = ""):
        try:
            response = requests.request(verbe, self.config.url(APIS_CONTEXT + path), auth = self.config.credential(), proxies = self.config.proxyDict, timeout=self.timeout)
            self._check(response)
            return response
        except RequestException:
            raise GraviteeRequestError(msg = "Error Connecting to server")

    def _check(self, response):
        if not response.status_code:
            raise GraviteeRequestError(msg = "Request error")
        if response.status_code == 400 and not response:
            error = response.json()
            raise GraviteeRequestError(msg = error['message'], error_code = error['http_status'] )
        if response.status_code > 400:
            raise GraviteeRequestError(msg = response.reason, error_code = response.status_code )