import logging
import json

from roboswag import APIModel


class {{ class_name }}(APIModel):
{% if description %}    """**Description:** {{ description }}"""
{% endif %}
    def __init__(self, url):
        super().__init__(base_url=url)
{% for endpoint in endpoints %}
{{ endpoint.method_signature }}{% if endpoint.body %}, validate_payload=True, overwrite_body=None{% endif %}{% if endpoint.headers %}, overwrite_headers=None{% endif %}{% if endpoint.query %}, overwrite_query=None{% endif %}):
{% if (endpoint.summary or endpoint.description) %}        """{% if endpoint.summary %}
        **Summary:** {{ endpoint.summary }}{% endif %}{% if endpoint.description %}

        **Description:** {{ endpoint.description }}{% endif %}
        """{% endif %}
{%- if endpoint.headers %}
        headers = {
{%- for param in endpoint.headers %}
            "{{ param.name }}": {{ param.python_name }}{{ "," if not loop.last else "" }}
{%- endfor %}
        }
        if overwrite_headers:
            headers = overwrite_headers
{% endif %}
{%- if endpoint.query %}
        _query = {
{%- for param in endpoint.query %}
            "{{ param.name }}": {{ param.python_name }}{{ "," if not loop.last else "" }}
{%- endfor %}
        }
        if overwrite_query:
            _query = overwrite_query
{% endif %}
{%- if endpoint.body %}
        if validate_payload:
        {%- if endpoint.body.schema %}
            schema = {{ endpoint.body.schema }}
            self.validate.schema(json.loads(body), schema)
        {%- endif %}

        _body = {{ endpoint.body.python_name }}

        if overwrite_body:
            _body = overwrite_body
{% endif %}
        response = self.{{ endpoint.http_method }}({{ "f" if "{" in endpoint.url else "" }}"{{ endpoint.url }}"{% if endpoint.headers %}, headers=headers{% endif %}{% if endpoint.query %}, query=_query{% endif %}{% if endpoint.body %}, body=_body{% endif %}, status=exp_status)

        if validate_schema:{% for status_code, resp in endpoint.responses.items() %}
        {%- if resp.schema %}
            {% if not loop.first %}el{% endif %}if response.status_code == {{ status_code }}:
                schema = {{ resp.schema }}
                self.validate.schema(response.json(), schema)
        {%- elif status_code != "default" %}
            {% if not loop.first %}el{% endif %}if response.status_code == {{ status_code }}:
                self.validate.error(response, "{{ resp.description }}")
        {%- else %}
            {% if not loop.first %}el{% endif %}if response.status_code == "default":
                self.validate.error(response, "{{ resp.description }}")
        {%- endif %}{% endfor %}
            else:
                logging.error(f"Received status code ({response.status_code}) is not expected by the API specification")
                assert False

        return response
{% endfor %}
