import json
from urllib import parse as urllib
from abc import ABC, abstractmethod
from lib.common import rest_client
from lib.services.api_gateway.base_client import BaseClient


class PathsClient(BaseClient):
    """Service client for API Gateway Paths resource."""

    def __init__(self, auth_provider, service, region, client=None, **kwargs):
        super(PathsClient, self).__init__(auth_provider, service, region, **kwargs)
        self.client = client

    def _parse_response(self, resp, body, schema):
        """Parse and validate response."""
        if body:
            body = json.loads(body)
        else:
            body = {}
        self.validate_response(schema, resp, body)
        return rest_client.ResponseBody(resp, body)

    def list_paths(self, api_id, **params):
        """List paths for an API."""
        url = self.client.get_paths_list_path(self.project_name, api_id)
        if params:
            url += f"?{urllib.urlencode(params)}"
        resp, body = self.get(url)
        return self._parse_response(
            resp, body, self.client.get_schema().list_paths
        )

    def create_path(self, api_id, **kwargs):
        """Create a path for an API."""
        url = self.client.get_paths_list_path(self.project_name, api_id)
        post_body = json.dumps(kwargs)
        resp, body = self.post(url, post_body)
        return self._parse_response(
            resp, body, self.client.get_schema().create_path
        )

    def show_path(self, path_id):
        """Show path details."""
        url = self.client.get_path_detail_path(self.project_name, path_id)
        resp, body = self.get(url)
        return self._parse_response(
            resp, body, self.client.get_schema().show_path
        )

    def delete_path(self, path_id, if_match=None):
        """Delete a path."""
        url = self.client.get_path_detail_path(self.project_name, path_id)
        headers = {"If-Match": if_match} if if_match else None
        resp, body = self.delete(url, headers=headers, extra_headers=True)
        return self._parse_response(
            resp, body, self.client.get_schema().delete_path
        )


class PathsClientInterface(ABC):
    """Interface for cloud-specific implementations."""

    @abstractmethod
    def get_schema(self):
        """Return response schemas module."""
        pass

    @abstractmethod
    def get_paths_list_path(self, project, api_id):
        """Return API endpoint path for listing paths."""
        pass

    @abstractmethod
    def get_path_detail_path(self, project, path_id):
        """Return API endpoint path for path details."""
        pass
