# coding: utf-8

"""
    Carrier API

    **Seaplane Global Messaging Service**  For information about authentication see [authentication](/docs/authentication)   # noqa: E501

    The version of the OpenAPI document: 1.1.0-beta
    Contact: support@seaplane.io
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""


from __future__ import annotations
import pprint
import re  # noqa: F401
import json


from typing import List, Optional
from pydantic import BaseModel, Field, StrictStr, conlist, constr, validator
from seaplane.gen.carrier.models.cors import Cors


class HTTPServerConfig(BaseModel):
    """
    HTTP server configuration
    """

    address: Optional[StrictStr] = Field(
        None,
        description="An alternative address to host from. If left empty the service wide address is used.",
    )
    path: Optional[constr(strict=True)] = Field(
        "/", description="The endpoint path to listen for POST requests."
    )
    ws_path: Optional[StrictStr] = Field(
        None, description="The endpoint path to create websocket connections from."
    )
    ws_welcome_message: Optional[StrictStr] = Field(
        None,
        description="An optional message to deliver to fresh websocket connections.",
    )
    ws_rate_limit_message: Optional[StrictStr] = Field(
        None,
        description="An optional message to delivery to websocket connections that are rate limited.",
    )
    allowed_verbs: Optional[conlist(StrictStr)] = Field(
        None, description="An array of verbs that are allowed for the path endpoint."
    )
    timeout: Optional[StrictStr] = Field(
        None,
        description="Timeout for requests. If a consumed messages takes longer than this to be delivered the connection is closed, but the message may still be delivered.",
    )
    rate_limit: Optional[StrictStr] = Field(
        None, description="An optional rate limit to throttle requests by."
    )
    cert_file: Optional[StrictStr] = Field(
        None,
        description="Enable TLS by specifying a certificate and key file. Only valid with a custom address.",
    )
    key_file: Optional[StrictStr] = Field(
        None,
        description="Enable TLS by specifying a certificate and key file. Only valid with a custom address.",
    )
    cors: Optional[Cors] = None
    __properties = [
        "address",
        "path",
        "ws_path",
        "ws_welcome_message",
        "ws_rate_limit_message",
        "allowed_verbs",
        "timeout",
        "rate_limit",
        "cert_file",
        "key_file",
        "cors",
    ]

    @validator("path")
    def path_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"[\/].*", value):
            raise ValueError(r"must validate the regular expression /[\/].*/")
        return value

    @validator("allowed_verbs")
    def allowed_verbs_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        for i in value:
            if i not in ("GET", "POST", "PUT", "DELETE"):
                raise ValueError(
                    "each list item must be one of ('GET', 'POST', 'PUT', 'DELETE')"
                )
        return value

    class Config:
        """Pydantic configuration"""

        allow_population_by_field_name = True
        validate_assignment = True

    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.dict(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> HTTPServerConfig:
        """Create an instance of HTTPServerConfig from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self):
        """Returns the dictionary representation of the model using alias"""
        _dict = self.dict(by_alias=True, exclude={}, exclude_none=True)
        # override the default output from pydantic by calling `to_dict()` of cors
        if self.cors:
            _dict["cors"] = self.cors.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: dict) -> HTTPServerConfig:
        """Create an instance of HTTPServerConfig from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return HTTPServerConfig.parse_obj(obj)

        _obj = HTTPServerConfig.parse_obj(
            {
                "address": obj.get("address"),
                "path": obj.get("path") if obj.get("path") is not None else "/",
                "ws_path": obj.get("ws_path"),
                "ws_welcome_message": obj.get("ws_welcome_message"),
                "ws_rate_limit_message": obj.get("ws_rate_limit_message"),
                "allowed_verbs": obj.get("allowed_verbs"),
                "timeout": obj.get("timeout"),
                "rate_limit": obj.get("rate_limit"),
                "cert_file": obj.get("cert_file"),
                "key_file": obj.get("key_file"),
                "cors": Cors.from_dict(obj.get("cors"))
                if obj.get("cors") is not None
                else None,
            }
        )
        return _obj
