# WARNING: Do not edit by hand, this file was generated by Crank:
#
#   https://github.com/gocardless/crank
#

import re

from .. import list_response
from ..api_response import ApiResponse

class BaseService(object):
    """Base class for API service classes."""

    def __init__(self, api_client):
        self._api_client = api_client

    def _perform_request(self, method, path, params):
        if method == 'GET':
            return self._api_client.get(path, params=params)

        if method == 'POST':
            body = {self._envelope_key(): params}
            return self._api_client.post(path, body=body)

        if method == 'PUT':
            body = {self._envelope_key(): params}
            return self._api_client.put(path, body=body)

        raise ValueError('Invalid method "{}"'.format(method))

    def _envelope_key(self):
        return type(self).RESOURCE_NAME

    def _resource_for(self, response):
        api_response = ApiResponse(response)

        data = api_response.body[self._envelope_key()]
        klass = type(self).RESOURCE_CLASS
        if isinstance(data, dict):
            return klass(data, api_response)
        else:
            records = [klass(item, api_response) for item in data]
            return list_response.ListResponse(records, api_response)

    def _sub_url_params(self, url, params):
        return re.sub(r':(\w+)', lambda match: params[match.group(1)], url)

