from typing import Any, Dict, Type, TypeVar, Tuple, Optional, BinaryIO, TextIO, TYPE_CHECKING

{% if model.additional_properties %}
from typing import List

{% endif %}

from attrs import define as _attrs_define
from attrs import field as _attrs_field
{% if model.is_multipart_body %}
import json
{% endif %}

from ..types import UNSET, Unset

{% for relative in model.relative_imports %}
{{ relative }}
{% endfor %}

{% for lazy_import in model.lazy_imports %}
{% if loop.first %}
if TYPE_CHECKING:
{% endif %}
  {{ lazy_import }}
{% endfor %}


{% if model.additional_properties %}
{% set additional_property_type = 'Any' if model.additional_properties == True else model.additional_properties.get_type_string(quoted=not model.additional_properties.is_base_type) %}
{% endif %}

{% set class_name = model.class_info.name %}
{% set module_name = model.class_info.module_name %}

{% from "helpers.jinja" import safe_docstring %}

T = TypeVar("T", bound="{{ class_name }}")

{% macro class_docstring_content(model) %}
    {% if model.title %}{{ model.title | wordwrap(116) }}

    {% endif -%}
    {%- if model.description %}{{ model.description | wordwrap(116) }}

    {% endif %}
    {% if not model.title and not model.description %}
    {# Leave extra space so that a section doesn't start on the first line #}

    {% endif %}
    {% if model.example %}
    Example:
        {{ model.example | string | wordwrap(112) | indent(12) }}

    {% endif %}
    {% if model.required_properties or model.optional_properties %}
    Attributes:
    {% for property in model.required_properties + model.optional_properties %}
        {{ property.to_docstring() | wordwrap(112) | indent(12) }}
    {% endfor %}{% endif %}
{% endmacro %}

@_attrs_define
class {{ class_name }}:
    {{ safe_docstring(class_docstring_content(model)) | indent(4) }}

    {% for property in model.required_properties + model.optional_properties %}
    {% if property.default is none and property.required %}
    {{ property.to_string() }}
    {% endif %}
    {% endfor %}
    {% for property in model.required_properties + model.optional_properties %}
    {% if property.default is not none or not property.required %}
    {{ property.to_string() }}
    {% endif %}
    {% endfor %}
    {% if model.additional_properties %}
    additional_properties: Dict[str, {{ additional_property_type }}] = _attrs_field(init=False, factory=dict)
    {% endif %}

{% macro _transform_property(property, content, multipart=False) %}
{% import "property_templates/" + property.template as prop_template %}
{% if prop_template.transform %}
{{ prop_template.transform(property, content, property.python_name, multipart=multipart) }}
{% elif multipart %}
{{ property.python_name }} = {{ content }} if isinstance({{ content }}, Unset) else (None, str({{ content }}).encode(), "text/plain")
{% else %}
{{ property.python_name }} = {{ content }}
{% endif %}

{% endmacro %}

{% macro _prepare_field_dict(multipart=False) %}
field_dict: Dict[str, Any] = {}
{% if model.additional_properties %}
{% if model.additional_properties.template %}{# Can be a bool instead of an object #}
    {% import "property_templates/" + model.additional_properties.template as prop_template %}
{% else %}
    {% set prop_template = None %}
{% endif %}
{% if prop_template and prop_template.transform %}
for prop_name, prop in self.additional_properties.items():
    {{ prop_template.transform(model.additional_properties, "prop", "field_dict[prop_name]", multipart=multipart, declare_type=false) | indent(4) }}
{% elif multipart %}
field_dict.update({
    key: (None, str(value).encode(), "text/plain")
    for key, value in self.additional_properties.items()
})
{% else %}
field_dict.update(self.additional_properties)
{%- endif -%}
{%- endif -%}
{% endmacro %}

{% macro _to_dict() %}
{% for property in model.required_properties + model.optional_properties -%}
{{ _transform_property(property, "self." + property.python_name) }}
{% endfor %}

{{ _prepare_field_dict() }}
{% if model.required_properties | length > 0 or model.optional_properties | length > 0 %}
field_dict.update({
    {% for property in model.required_properties + model.optional_properties %}
    {% if property.required %}
    "{{ property.name }}": {{ property.python_name }},
    {% endif %}
    {% endfor %}
})
{% endif %}
{% for property in model.optional_properties %}
{% if not property.required %}
if {{ property.python_name }} is not UNSET:
    field_dict["{{ property.name }}"] = {{ property.python_name }}
{% endif %}
{% endfor %}

return field_dict
{% endmacro %}

    def to_dict(self) -> Dict[str, Any]:
    {% for lazy_import in model.lazy_imports %}
        {{ lazy_import }}
    {% endfor %}
        {{ _to_dict() | indent(8) }}

{% if model.is_multipart_body %}
    def to_multipart(self) -> List[Tuple[str, Any]]:
        field_list: List[Tuple[str, Any]] = []
        {% for property in model.required_properties + model.optional_properties %}
        {% if property.__class__.__name__ == 'ListProperty' %}
        {% if not property.required %}
        for cont in self.{{ property.python_name }} or []:
        {% else %}
        for cont in self.{{ property.python_name }}:
        {% endif %}
            {{ _transform_property(property.inner_property, "cont", True) | indent(12) }}
            field_list.append(("{{ property.python_name }}", {{property.inner_property.python_name}}))

        {% else %}
        {{ _transform_property(property, "self." + property.python_name, True) | indent(8) }}
        {% if not property.required %}
        if {{ property.python_name }} is not UNSET:
            field_list.append(("{{ property.python_name }}", {{property.python_name}}))
        {% else %}
        field_list.append(("{{ property.python_name }}", {{property.python_name}}))
        {% endif %}
        {% endif %}
        {% endfor %}

        {{ _prepare_field_dict(True) | indent(8) }}

        field_list += list(field_dict.items())

        return field_list

{% endif %}

    @classmethod
    def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
    {% for lazy_import in model.lazy_imports %}
        {{ lazy_import }}
    {% endfor %}
        d = src_dict.copy()
{% for property in model.required_properties + model.optional_properties %}
    {% if property.required %}
        {% set property_source = 'd.pop("' + property.name + '")' %}
    {% else %}
        {% set property_source = 'd.pop("' + property.name + '", UNSET)' %}
    {% endif %}
    {% import "property_templates/" + property.template as prop_template %}
    {% if prop_template.construct %}
        {{ prop_template.construct(property, property_source) | indent(8) }}
    {% else %}
        {{ property.python_name }} = {{ property_source }}
    {% endif %}

{% endfor %}
        {{ module_name }}_obj = cls(
{% for property in model.required_properties + model.optional_properties %}
            {{ property.python_name }}={{ property.python_name }},
{% endfor %}
        )

{% if model.additional_properties %}
    {% if model.additional_properties.template %}{# Can be a bool instead of an object #}
        {% import "property_templates/" + model.additional_properties.template as prop_template %}

{% if model.additional_properties.lazy_imports %}
    {% for lazy_import in model.additional_properties.lazy_imports %}
        {{ lazy_import }}
    {% endfor %}
{% endif %}
    {% else %}
        {% set prop_template = None %}
    {% endif %}
    {% if prop_template and prop_template.construct %}
        additional_properties = {}
        for prop_name, prop_dict in d.items():
            {{ prop_template.construct(model.additional_properties, "prop_dict") | indent(12) }}
            additional_properties[prop_name] = {{ model.additional_properties.python_name }}

        {{ module_name }}_obj.additional_properties = additional_properties
    {% else %}
        {{ module_name }}_obj.additional_properties = d
    {% endif %}
{% endif %}
        return {{ module_name }}_obj

    {% if model.additional_properties %}
    @property
    def additional_keys(self) -> List[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> {{ additional_property_type }}:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: {{ additional_property_type }}) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties
    {% endif %}
