# coding: utf-8

"""
    LUSID API

    FINBOURNE Technology  # noqa: E501

    Contact: info@finbourne.com
    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, Dict, Optional, Any, Union, TYPE_CHECKING
from typing_extensions import Annotated
from pydantic.v1 import BaseModel, StrictStr, StrictInt, StrictBool, StrictFloat, StrictBytes, Field, validator, ValidationError, conlist, constr
from datetime import datetime
from lusid.models.interest_rate_swap import InterestRateSwap
from lusid.models.lusid_instrument import LusidInstrument
from lusid.models.premium import Premium
from lusid.models.time_zone_conventions import TimeZoneConventions

class InterestRateSwaption(LusidInstrument):
    """
    LUSID representation of an Interest Rate Swaption.  # noqa: E501
    """
    start_date: datetime = Field(description="The start date of the instrument. This is normally synonymous with the trade-date.", alias="startDate")
    pay_or_receive_fixed:  StrictStr = Field(...,alias="payOrReceiveFixed", description="Pay or Receive the fixed leg of the underlying swap.    Supported string (enumeration) values are: [Pay, Receive].") 
    premium: Optional[Premium] = None
    delivery_method:  StrictStr = Field(...,alias="deliveryMethod", description="How does the option settle    Supported string (enumeration) values are: [Cash, Physical].") 
    swap: Optional[InterestRateSwap] = None
    time_zone_conventions: Optional[TimeZoneConventions] = Field(default=None, alias="timeZoneConventions")
    underlying: Optional[LusidInstrument] = None
    delivery_days: Optional[StrictInt] = Field(default=None, description="Number of business days between exercise date and settlement of the option payoff or underlying.                Defaults to 0.", alias="deliveryDays")
    business_day_convention:  Optional[StrictStr] = Field(None,alias="businessDayConvention", description="Business day convention for option exercise date to settlement date calculation.  Supported string (enumeration) values are: [NoAdjustment, Previous, P, Following, F, ModifiedPrevious, MP, ModifiedFollowing, MF, HalfMonthModifiedFollowing, Nearest].                Defaults to \"F\".") 
    settlement_calendars: Optional[List[StrictStr]] = Field(default=None, description="Holiday calendars for option exercise date to settlement date calculation.", alias="settlementCalendars")
    instrument_type:  StrictStr = Field(...,alias="instrumentType", description="The available values are: QuotedSecurity, InterestRateSwap, FxForward, Future, ExoticInstrument, FxOption, CreditDefaultSwap, InterestRateSwaption, Bond, EquityOption, FixedLeg, FloatingLeg, BespokeCashFlowsLeg, Unknown, TermDeposit, ContractForDifference, EquitySwap, CashPerpetual, CapFloor, CashSettled, CdsIndex, Basket, FundingLeg, FxSwap, ForwardRateAgreement, SimpleInstrument, Repo, Equity, ExchangeTradedOption, ReferenceInstrument, ComplexBond, InflationLinkedBond, InflationSwap, SimpleCashFlowLoan, TotalReturnSwap, InflationLeg, FundShareClass, FlexibleLoan, UnsettledCash, Cash, MasteredInstrument, LoanFacility, FlexibleDeposit, FlexibleRepo") 
    additional_properties: Dict[str, Any] = {}
    __properties = ["instrumentType", "startDate", "payOrReceiveFixed", "premium", "deliveryMethod", "swap", "timeZoneConventions", "underlying", "deliveryDays", "businessDayConvention", "settlementCalendars"]

    @validator('instrument_type')
    def instrument_type_validate_enum(cls, value):
        """Validates the enum"""

        # Finbourne have removed enum validation on all models, except for this use case:
        # Workflow and notification application SDK use the property name 'type' as the discriminator on a number of classes.
        # During instantiation, the value of 'type' is checked against the enum values, 
        

        # check it's a class that uses the 'type' property as a discriminator
        # list of classes can be found by searching for 'actual_instance: Union[' in the generated code
        if 'InterestRateSwaption' not in [ 
                                    # For notification application classes
                                    'AmazonSqsNotificationType',
                                    'AmazonSqsNotificationTypeResponse',
                                    'AmazonSqsPrincipalAuthNotificationType',
                                    'AmazonSqsPrincipalAuthNotificationTypeResponse',
                                    'AzureServiceBusTypeResponse',
                                    'AzureServiceBusNotificationType',
                                    'EmailNotificationType',
                                    'EmailNotificationTypeResponse',
                                    'SmsNotificationType',
                                    'SmsNotificationTypeResponse',
                                    'WebhookNotificationType',
                                    'WebhookNotificationTypeResponse',
                        
                                    # For workflow application classes
                                    'CreateChildTasksAction', 
                                    'RunWorkerAction', 
                                    'TriggerParentTaskAction',
                                    'CreateChildTasksActionResponse', 
                                    'RunWorkerActionResponse',
                                    'TriggerParentTaskActionResponse',
                                    'CreateNewTaskActivity',
                                    'UpdateMatchingTasksActivity',
                                    'CreateNewTaskActivityResponse', 
                                    'UpdateMatchingTasksActivityResponse',
                                    'Fail', 
                                    'GroupReconciliation', 
                                    'HealthCheck', 
                                    'LuminesceView', 
                                    'SchedulerJob', 
                                    'Sleep',
                                    'FailResponse', 
                                    'GroupReconciliationResponse', 
                                    'HealthCheckResponse', 
                                    'LuminesceViewResponse', 
                                    'SchedulerJobResponse', 
                                    'SleepResponse',
                                    'Library',
                                    'LibraryResponse',
                                    'DayRegularity',
                                    'RelativeMonthRegularity',
                                    'SpecificMonthRegularity',
                                    'WeekRegularity',
                                    'YearRegularity',
                                    'LusidEntityDataQualityCheck',
                                    'LusidEntityDataQualityCheckResponse']:
           return value
        
        # Only validate the 'type' property of the class
        if "instrument_type" != "type":
            return value

        if value not in ['QuotedSecurity', 'InterestRateSwap', 'FxForward', 'Future', 'ExoticInstrument', 'FxOption', 'CreditDefaultSwap', 'InterestRateSwaption', 'Bond', 'EquityOption', 'FixedLeg', 'FloatingLeg', 'BespokeCashFlowsLeg', 'Unknown', 'TermDeposit', 'ContractForDifference', 'EquitySwap', 'CashPerpetual', 'CapFloor', 'CashSettled', 'CdsIndex', 'Basket', 'FundingLeg', 'FxSwap', 'ForwardRateAgreement', 'SimpleInstrument', 'Repo', 'Equity', 'ExchangeTradedOption', 'ReferenceInstrument', 'ComplexBond', 'InflationLinkedBond', 'InflationSwap', 'SimpleCashFlowLoan', 'TotalReturnSwap', 'InflationLeg', 'FundShareClass', 'FlexibleLoan', 'UnsettledCash', 'Cash', 'MasteredInstrument', 'LoanFacility', 'FlexibleDeposit', 'FlexibleRepo']:
            raise ValueError("must be one of enum values ('QuotedSecurity', 'InterestRateSwap', 'FxForward', 'Future', 'ExoticInstrument', 'FxOption', 'CreditDefaultSwap', 'InterestRateSwaption', 'Bond', 'EquityOption', 'FixedLeg', 'FloatingLeg', 'BespokeCashFlowsLeg', 'Unknown', 'TermDeposit', 'ContractForDifference', 'EquitySwap', 'CashPerpetual', 'CapFloor', 'CashSettled', 'CdsIndex', 'Basket', 'FundingLeg', 'FxSwap', 'ForwardRateAgreement', 'SimpleInstrument', 'Repo', 'Equity', 'ExchangeTradedOption', 'ReferenceInstrument', 'ComplexBond', 'InflationLinkedBond', 'InflationSwap', 'SimpleCashFlowLoan', 'TotalReturnSwap', 'InflationLeg', 'FundShareClass', 'FlexibleLoan', 'UnsettledCash', 'Cash', 'MasteredInstrument', 'LoanFacility', 'FlexibleDeposit', 'FlexibleRepo')")
        return value

    class Config:
        """Pydantic configuration"""
        allow_population_by_field_name = True
        validate_assignment = True

    def __str__(self):
        """For `print` and `pprint`"""
        return pprint.pformat(self.dict(by_alias=False))

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    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) -> InterestRateSwaption:
        """Create an instance of InterestRateSwaption 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={
                            "additional_properties"
                          },
                          exclude_none=True)
        # override the default output from pydantic by calling `to_dict()` of premium
        if self.premium:
            _dict['premium'] = self.premium.to_dict()
        # override the default output from pydantic by calling `to_dict()` of swap
        if self.swap:
            _dict['swap'] = self.swap.to_dict()
        # override the default output from pydantic by calling `to_dict()` of time_zone_conventions
        if self.time_zone_conventions:
            _dict['timeZoneConventions'] = self.time_zone_conventions.to_dict()
        # override the default output from pydantic by calling `to_dict()` of underlying
        if self.underlying:
            _dict['underlying'] = self.underlying.to_dict()
        # 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

        # set to None if business_day_convention (nullable) is None
        # and __fields_set__ contains the field
        if self.business_day_convention is None and "business_day_convention" in self.__fields_set__:
            _dict['businessDayConvention'] = None

        # set to None if settlement_calendars (nullable) is None
        # and __fields_set__ contains the field
        if self.settlement_calendars is None and "settlement_calendars" in self.__fields_set__:
            _dict['settlementCalendars'] = None

        return _dict

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

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

        _obj = InterestRateSwaption.parse_obj({
            "instrument_type": obj.get("instrumentType"),
            "start_date": obj.get("startDate"),
            "pay_or_receive_fixed": obj.get("payOrReceiveFixed"),
            "premium": Premium.from_dict(obj.get("premium")) if obj.get("premium") is not None else None,
            "delivery_method": obj.get("deliveryMethod"),
            "swap": InterestRateSwap.from_dict(obj.get("swap")) if obj.get("swap") is not None else None,
            "time_zone_conventions": TimeZoneConventions.from_dict(obj.get("timeZoneConventions")) if obj.get("timeZoneConventions") is not None else None,
            "underlying": LusidInstrument.from_dict(obj.get("underlying")) if obj.get("underlying") is not None else None,
            "delivery_days": obj.get("deliveryDays"),
            "business_day_convention": obj.get("businessDayConvention"),
            "settlement_calendars": obj.get("settlementCalendars")
        })
        # store additional fields in additional_properties
        for _key in obj.keys():
            if _key not in cls.__properties:
                _obj.additional_properties[_key] = obj.get(_key)

        return _obj

InterestRateSwaption.update_forward_refs()
