# coding: utf-8

"""
    FreeClimb API

    FreeClimb is a cloud-based application programming interface (API) that puts the power of the Vail platform in your hands. FreeClimb simplifies the process of creating applications that can use a full range of telephony features without requiring specialized or on-site telephony equipment. Using the FreeClimb REST API to write applications is easy! You have the option to use the language of your choice or hit the API directly. Your application can execute a command by issuing a RESTful request to the FreeClimb API. The base URL to send HTTP requests to the FreeClimb REST API is: /apiserver. FreeClimb authenticates and processes your request.

    The version of the OpenAPI document: 1.0.0
    Contact: support@freeclimb.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


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

from pydantic import BaseModel, ConfigDict, Field
from typing import Any, ClassVar, Dict, List, Optional
from freeclimb.models.percl_command import PerclCommand
from pydantic import StrictStr
from typing import Optional, Set
from typing_extensions import Self


class PerclScript(
    BaseModel, populate_by_name=True, validate_assignment=True, protected_namespaces=()
):
    """
    A PerCL script to be returned to the FreeClimb servers in FreeClimb applications
    """  # noqa: E501

    commands: Optional[List[PerclCommand]] = Field(
        default=None, description="A JSON array of PerCL commands"
    )

    __properties: ClassVar[List[str]] = ["commands"]

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

    def to_percl_dict(self, instance_dict):
        if "command" in instance_dict == False:
            raise AttributeError(
                "{0} has no attribute '{1}'".format(instance_dict, "command")
            )
        command = instance_dict.get("command")
        attribute_map = {}
        for key, value in instance_dict.items():
            if key == "command":
                continue
            if value is None:
                continue
            if isinstance(value, dict) and "command" in value:
                attribute_map[key] = self.to_percl_dict(value)
                continue
            if isinstance(value, list):
                attribute_map[key] = [self.to_percl_dict(item) for item in value]
                continue
            attribute_map[key] = value
        percl_dict = {command: attribute_map}
        return percl_dict

    def to_json(self):
        return json.dumps(
            [self.to_percl_dict(command.to_dict()) for command in self.commands]
        )

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

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of each item in commands (list)
        _items = []
        if self.commands:
            for _item_commands in self.commands:
                if _item_commands:
                    _items.append(_item_commands.to_dict())
            _dict["commands"] = _items
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of PerclScript from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate(
            {
                "commands": (
                    [PerclCommand.from_dict(_item) for _item in obj["commands"]]
                    if obj.get("commands") is not None
                    else None
                )
            }
        )
        return _obj
