# coding: utf-8

"""
    Zuora API Reference

    REST API reference for the Zuora Billing, Payments, and Central Platform! Check out the [REST API Overview](https://www.zuora.com/developer/api-references/api/overview/).

    The version of the OpenAPI document: 2024-05-20
    Contact: docs@zuora.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 datetime import date
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from zuora_sdk.models.expanded_debit_taxation_item import ExpandedDebitTaxationItem
from typing import Optional, Set
from typing_extensions import Self

class ExpandedDebitMemoItem(BaseModel):
    """
    ExpandedDebitMemoItem
    """ # noqa: E501
    # avoid validation
    def __init__(self, **kwargs):
        # Directly assign values without validation using `construct()`
        model = self.construct(**kwargs)
        self.__dict__.update(model.__dict__)

        _dict_all = convert_snake_dict_to_camel(kwargs, self.model_fields, self.__properties)

        _dict = self.to_alias_dict(_dict_all)
        for field_name, field_info in self.model_fields.items():
            alias = field_info.alias or field_name
            if alias in _dict:
                self.__dict__[field_name] = _dict.get(alias)
        self.update_additional_properties(self, _dict_all)
        pass

    def __setattr__(self, name, value):
        # Override setattr to bypass validation when setting attributes
        object.__setattr__(self, name, value)

    amount: Optional[Union[StrictFloat, StrictInt]] = None
    amount_without_tax: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="amountWithoutTax")
    applied_to_item_id: Optional[StrictStr] = Field(default=None, alias="appliedToItemId")
    applied_to_others_amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="appliedToOthersAmount")
    be_applied_by_others_amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="beAppliedByOthersAmount")
    charge_date: Optional[StrictStr] = Field(default=None, alias="chargeDate")
    credit_memo_item_id: Optional[StrictStr] = Field(default=None, alias="creditMemoItemId")
    exclude_item_billing_from_revenue_accounting: Optional[StrictBool] = Field(default=None, alias="excludeItemBillingFromRevenueAccounting")
    description: Optional[StrictStr] = None
    item_ship_to_contact_id: Optional[StrictStr] = Field(default=None, alias="itemShipToContactId")
    item_sold_to_contact_id: Optional[StrictStr] = Field(default=None, alias="itemSoldToContactId")
    item_sold_to_contact_snapshot_id: Optional[StrictStr] = Field(default=None, alias="itemSoldToContactSnapshotId")
    processing_type: Optional[StrictStr] = Field(default=None, alias="processingType")
    quantity: Optional[Union[StrictFloat, StrictInt]] = None
    service_end_date: Optional[date] = Field(default=None, alias="serviceEndDate")
    service_start_date: Optional[date] = Field(default=None, alias="serviceStartDate")
    sku: Optional[StrictStr] = None
    source_item_type: Optional[StrictStr] = Field(default=None, alias="sourceItemType")
    charge_name: Optional[StrictStr] = Field(default=None, alias="chargeName")
    charge_number: Optional[StrictStr] = Field(default=None, alias="chargeNumber")
    tax_amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="taxAmount")
    tax_code_name: Optional[StrictStr] = Field(default=None, alias="taxCodeName")
    tax_exempt_amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="taxExemptAmount")
    tax_mode: Optional[StrictStr] = Field(default=None, alias="taxMode")
    unit_of_measure: Optional[StrictStr] = Field(default=None, alias="unitOfMeasure")
    unit_price: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="unitPrice")
    subscription_id: Optional[StrictStr] = Field(default=None, alias="subscriptionId")
    subscription_number: Optional[StrictStr] = Field(default=None, alias="subscriptionNumber")
    invoice_item_id: Optional[StrictStr] = Field(default=None, alias="invoiceItemId")
    product_rate_plan_charge_id: Optional[StrictStr] = Field(default=None, alias="productRatePlanChargeId")
    rate_plan_charge_id: Optional[StrictStr] = Field(default=None, alias="ratePlanChargeId")
    debit_memo_id: Optional[StrictStr] = Field(default=None, alias="debitMemoId")
    balance: Optional[Union[StrictFloat, StrictInt]] = None
    reflect_discount_in_net_amount: Optional[StrictBool] = Field(default=None, alias="reflectDiscountInNetAmount")
    id: Optional[StrictStr] = None
    created_by_id: Optional[StrictStr] = Field(default=None, alias="createdById")
    created_date: Optional[StrictStr] = Field(default=None, alias="createdDate")
    updated_by_id: Optional[StrictStr] = Field(default=None, alias="updatedById")
    updated_date: Optional[StrictStr] = Field(default=None, alias="updatedDate")
    recognized_revenue_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="recognizedRevenueAccountingCodeId")
    account_receivable_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="accountReceivableAccountingCodeId")
    deferred_revenue_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="deferredRevenueAccountingCodeId")
    journal_entry_id: Optional[StrictStr] = Field(default=None, alias="journalEntryId")
    sold_to_contact_snapshot_id: Optional[StrictStr] = Field(default=None, alias="soldToContactSnapshotId")
    bill_to_contact_snapshot_id: Optional[StrictStr] = Field(default=None, alias="billToContactSnapshotId")
    ship_to_contact_snapshot_id: Optional[StrictStr] = Field(default=None, alias="shipToContactSnapshotId")
    subscription_owner_id: Optional[StrictStr] = Field(default=None, alias="subscriptionOwnerId")
    subscription: Optional[ExpandedSubscription] = None
    rate_plan_charge: Optional[ExpandedRatePlanCharge] = Field(default=None, alias="ratePlanCharge")
    subscription_owner: Optional[ExpandedAccount] = Field(default=None, alias="subscriptionOwner")
    debit_taxation_items: Optional[List[ExpandedDebitTaxationItem]] = Field(default=None, alias="debitTaxationItems")
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["amount", "amountWithoutTax", "appliedToItemId", "appliedToOthersAmount", "beAppliedByOthersAmount", "chargeDate", "creditMemoItemId", "excludeItemBillingFromRevenueAccounting", "description", "itemShipToContactId", "itemSoldToContactId", "itemSoldToContactSnapshotId", "processingType", "quantity", "serviceEndDate", "serviceStartDate", "sku", "sourceItemType", "chargeName", "chargeNumber", "taxAmount", "taxCodeName", "taxExemptAmount", "taxMode", "unitOfMeasure", "unitPrice", "subscriptionId", "subscriptionNumber", "invoiceItemId", "productRatePlanChargeId", "ratePlanChargeId", "debitMemoId", "balance", "reflectDiscountInNetAmount", "id", "createdById", "createdDate", "updatedById", "updatedDate", "recognizedRevenueAccountingCodeId", "accountReceivableAccountingCodeId", "deferredRevenueAccountingCodeId", "journalEntryId", "soldToContactSnapshotId", "billToContactSnapshotId", "shipToContactSnapshotId", "subscriptionOwnerId", "subscription", "ratePlanCharge", "subscriptionOwner", "debitTaxationItems"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    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_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of ExpandedDebitMemoItem 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.
        * Fields in `self.additional_properties` are added to the output dict.
        """
        excluded_fields: Set[str] = set([
            "additional_properties",
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of subscription
        if self.subscription:
            _dict['subscription'] = self.subscription.to_dict()
        # override the default output from pydantic by calling `to_dict()` of rate_plan_charge
        if self.rate_plan_charge:
            _dict['ratePlanCharge'] = self.rate_plan_charge.to_dict()
        # override the default output from pydantic by calling `to_dict()` of subscription_owner
        if self.subscription_owner:
            _dict['subscriptionOwner'] = self.subscription_owner.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in debit_taxation_items (list)
        _items = []
        if self.debit_taxation_items:
            for _item_debit_taxation_items in self.debit_taxation_items:
                if _item_debit_taxation_items:
                    _items.append(_item_debit_taxation_items.to_dict())
            _dict['debitTaxationItems'] = _items
        # puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value

        return _dict

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

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

        obj = convert_snake_dict_to_camel(obj, cls.model_fields, cls.__properties)

        _obj = cls.model_validate(cls.to_alias_dict(obj))
        return cls.update_additional_properties(_obj, obj)

    @classmethod
    def update_additional_properties(cls, obj, _dict: Optional[Dict[str, Any]]):
        # store additional fields in additional_properties

        # store additional fields in additional_properties
        for _key in _dict.keys():
            if _key not in cls.__properties:
                obj.additional_properties[_key] = _dict.get(_key)


        return obj
        pass

    @classmethod
    def to_alias_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:

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

        return {
            "amount": obj.get("amount"),
            "amountWithoutTax": obj.get("amountWithoutTax"),
            "appliedToItemId": obj.get("appliedToItemId"),
            "appliedToOthersAmount": obj.get("appliedToOthersAmount"),
            "beAppliedByOthersAmount": obj.get("beAppliedByOthersAmount"),
            "chargeDate": obj.get("chargeDate"),
            "creditMemoItemId": obj.get("creditMemoItemId"),
            "excludeItemBillingFromRevenueAccounting": obj.get("excludeItemBillingFromRevenueAccounting"),
            "description": obj.get("description"),
            "itemShipToContactId": obj.get("itemShipToContactId"),
            "itemSoldToContactId": obj.get("itemSoldToContactId"),
            "itemSoldToContactSnapshotId": obj.get("itemSoldToContactSnapshotId"),
            "processingType": obj.get("processingType"),
            "quantity": obj.get("quantity"),
            "serviceEndDate": obj.get("serviceEndDate"),
            "serviceStartDate": obj.get("serviceStartDate"),
            "sku": obj.get("sku"),
            "sourceItemType": obj.get("sourceItemType"),
            "chargeName": obj.get("chargeName"),
            "chargeNumber": obj.get("chargeNumber"),
            "taxAmount": obj.get("taxAmount"),
            "taxCodeName": obj.get("taxCodeName"),
            "taxExemptAmount": obj.get("taxExemptAmount"),
            "taxMode": obj.get("taxMode"),
            "unitOfMeasure": obj.get("unitOfMeasure"),
            "unitPrice": obj.get("unitPrice"),
            "subscriptionId": obj.get("subscriptionId"),
            "subscriptionNumber": obj.get("subscriptionNumber"),
            "invoiceItemId": obj.get("invoiceItemId"),
            "productRatePlanChargeId": obj.get("productRatePlanChargeId"),
            "ratePlanChargeId": obj.get("ratePlanChargeId"),
            "debitMemoId": obj.get("debitMemoId"),
            "balance": obj.get("balance"),
            "reflectDiscountInNetAmount": obj.get("reflectDiscountInNetAmount"),
            "id": obj.get("id"),
            "createdById": obj.get("createdById"),
            "createdDate": obj.get("createdDate"),
            "updatedById": obj.get("updatedById"),
            "updatedDate": obj.get("updatedDate"),
            "recognizedRevenueAccountingCodeId": obj.get("recognizedRevenueAccountingCodeId"),
            "accountReceivableAccountingCodeId": obj.get("accountReceivableAccountingCodeId"),
            "deferredRevenueAccountingCodeId": obj.get("deferredRevenueAccountingCodeId"),
            "journalEntryId": obj.get("journalEntryId"),
            "soldToContactSnapshotId": obj.get("soldToContactSnapshotId"),
            "billToContactSnapshotId": obj.get("billToContactSnapshotId"),
            "shipToContactSnapshotId": obj.get("shipToContactSnapshotId"),
            "subscriptionOwnerId": obj.get("subscriptionOwnerId"),
            "subscription": ExpandedSubscription.from_dict(obj["subscription"]) if obj.get("subscription") is not None else None,
            "ratePlanCharge": ExpandedRatePlanCharge.from_dict(obj["ratePlanCharge"]) if obj.get("ratePlanCharge") is not None else None,
            "subscriptionOwner": ExpandedAccount.from_dict(obj["subscriptionOwner"]) if obj.get("subscriptionOwner") is not None else None,
            "debitTaxationItems": [ExpandedDebitTaxationItem.from_dict(_item) for _item in obj["debitTaxationItems"]] if obj.get("debitTaxationItems") is not None else None
        }
        return _obj
from zuora_sdk.models.expanded_account import ExpandedAccount
from zuora_sdk.models.expanded_rate_plan_charge import ExpandedRatePlanCharge
from zuora_sdk.models.expanded_subscription import ExpandedSubscription
# TODO: Rewrite to not use raise_errors
ExpandedDebitMemoItem.model_rebuild(raise_errors=False)


def convert_snake_dict_to_camel(_dict: dict, model_fields, properties):
    if not isinstance(_dict, dict):
        return _dict
    new_dict = {}
    for k, v in _dict.items():
        if k in model_fields:
            # model_fields: key is attribute name like bill_to_contact,
            alias = model_fields.get(k).alias or k
            new_dict[alias] = v
            pass
        else:
            new_key = snake_to_camel(k)
            if properties is not None and isinstance(properties, list) and new_key in properties:
                new_dict[new_key] = v
            else:
                new_dict[k] = v
    return new_dict
    pass


def snake_to_camel(name):
    if name is None or '_' not in name:
        return name
    components = name.split('_')
    return components[0] + ''.join(x.title() for x in components[1:])
