# 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.lusid_instrument import LusidInstrument
from lusid.models.premium import Premium
from lusid.models.time_zone_conventions import TimeZoneConventions

class EquityOption(LusidInstrument):
    """
    LUSID representation of a plain vanilla OTC Equity Option.  # noqa: E501
    """
    start_date: datetime = Field(description="The start date of the instrument. This is normally synonymous with the trade-date.", alias="startDate")
    option_maturity_date: datetime = Field(description="The maturity date of the option.", alias="optionMaturityDate")
    option_settlement_date: Optional[datetime] = Field(default=None, description="The settlement date of the option.", alias="optionSettlementDate")
    delivery_type:  StrictStr = Field(...,alias="deliveryType", description="Is the option cash settled or physical delivery of option    Supported string (enumeration) values are: [Cash, Physical].") 
    option_type:  StrictStr = Field(...,alias="optionType", description="Type of optionality for the option    Supported string (enumeration) values are: [Call, Put].") 
    strike: Union[StrictFloat, StrictInt] = Field(description="The strike of the option.")
    dom_ccy:  StrictStr = Field(...,alias="domCcy", description="The domestic currency of the instrument.") 
    underlying_identifier:  Optional[StrictStr] = Field(None,alias="underlyingIdentifier", description="The market identifier type of the underlying code, e.g RIC.    Supported string (enumeration) values are: [LusidInstrumentId, Isin, Sedol, Cusip, ClientInternal, Figi, RIC, QuotePermId, REDCode, BBGId, ICECode].  Optional field, should be used in combination with the Code field.  Not compatible with the Underlying field.") 
    code:  Optional[StrictStr] = Field(None,alias="code", description="The identifying code for the equity underlying, e.g. 'IBM.N'.  Optional field, should be used in combination with the UnderlyingIdentifier field.  Not compatible with the Underlying field.") 
    equity_option_type:  Optional[StrictStr] = Field(None,alias="equityOptionType", description="Equity option types. E.g. Vanilla (default), RightsIssue, Warrant.    Supported string (enumeration) values are: [Vanilla, RightsIssue, Warrant].") 
    number_of_shares: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="The amount of shares to exchange if the option is exercised.", alias="numberOfShares")
    premium: Optional[Premium] = None
    exercise_type:  Optional[StrictStr] = Field(None,alias="exerciseType", description="Type of optionality that is present; European, American.    Supported string (enumeration) values are: [European, American].  Defaults to \"European\" if not set.") 
    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 if not set.", 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\" if not set.") 
    settlement_calendars: Optional[List[StrictStr]] = Field(default=None, description="Holiday calendars for option exercise date to settlement date calculation.", alias="settlementCalendars")
    time_zone_conventions: Optional[TimeZoneConventions] = Field(default=None, alias="timeZoneConventions")
    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", "optionMaturityDate", "optionSettlementDate", "deliveryType", "optionType", "strike", "domCcy", "underlyingIdentifier", "code", "equityOptionType", "numberOfShares", "premium", "exerciseType", "underlying", "deliveryDays", "businessDayConvention", "settlementCalendars", "timeZoneConventions"]

    @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 'EquityOption' 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']:
           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) -> EquityOption:
        """Create an instance of EquityOption 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 underlying
        if self.underlying:
            _dict['underlying'] = self.underlying.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()
        # 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 option_settlement_date (nullable) is None
        # and __fields_set__ contains the field
        if self.option_settlement_date is None and "option_settlement_date" in self.__fields_set__:
            _dict['optionSettlementDate'] = None

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

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

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

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

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

        # 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) -> EquityOption:
        """Create an instance of EquityOption from a dict"""
        if obj is None:
            return None

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

        _obj = EquityOption.parse_obj({
            "instrument_type": obj.get("instrumentType"),
            "start_date": obj.get("startDate"),
            "option_maturity_date": obj.get("optionMaturityDate"),
            "option_settlement_date": obj.get("optionSettlementDate"),
            "delivery_type": obj.get("deliveryType"),
            "option_type": obj.get("optionType"),
            "strike": obj.get("strike"),
            "dom_ccy": obj.get("domCcy"),
            "underlying_identifier": obj.get("underlyingIdentifier"),
            "code": obj.get("code"),
            "equity_option_type": obj.get("equityOptionType"),
            "number_of_shares": obj.get("numberOfShares"),
            "premium": Premium.from_dict(obj.get("premium")) if obj.get("premium") is not None else None,
            "exercise_type": obj.get("exerciseType"),
            "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"),
            "time_zone_conventions": TimeZoneConventions.from_dict(obj.get("timeZoneConventions")) if obj.get("timeZoneConventions") is not None else None
        })
        # 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

EquityOption.update_forward_refs()
