# 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 datetime import datetime
from typing import Any, Dict, Optional, Union
from pydantic.v1 import Field, StrictBool, StrictFloat, StrictInt, StrictStr, constr, validator
from lusid.models.flow_conventions import FlowConventions
from lusid.models.instrument_leg import InstrumentLeg
from lusid.models.lusid_instrument import LusidInstrument

class EquitySwap(LusidInstrument):
    """
    LUSID representation of an Equity Swap.                This instrument has multiple legs, to see how legs are used in LUSID see [knowledge base article KA-02252](https://support.lusid.com/knowledgebase/article/KA-02252).                | Leg Index | Leg Identifier | Description |  | --------- | -------------- | ----------- |  | 1 | EquityLeg | Cash flows relating to the performance of the underlying equity. |  | 2 | FundingLeg | The funding leg of the swap. |  | 3 | EquityDividendLeg | Cash flows relating to dividend payments on the underlying equity (optional). |  # noqa: E501
    """
    start_date: datetime = Field(..., alias="startDate", description="The start date of the EquitySwap.")
    maturity_date: datetime = Field(..., alias="maturityDate", description="The final maturity date of the instrument. This means the last date on which the instruments makes a payment of any amount.  For the avoidance of doubt, that is not necessarily prior to its last sensitivity date for the purposes of risk; e.g. instruments such as  Constant Maturity Swaps (CMS) often have sensitivities to rates that may well be observed or set prior to the maturity date, but refer to a termination date beyond it.")
    code: constr(strict=True, min_length=1) = Field(..., description="The code of the underlying.")
    equity_flow_conventions: FlowConventions = Field(..., alias="equityFlowConventions")
    funding_leg: InstrumentLeg = Field(..., alias="fundingLeg")
    include_dividends: StrictBool = Field(..., alias="includeDividends", description="Dividend inclusion flag, if true dividends are included in the equity leg (total return).")
    initial_price: Union[StrictFloat, StrictInt] = Field(..., alias="initialPrice", description="The initial equity price of the Equity Swap.")
    notional_reset: StrictBool = Field(..., alias="notionalReset", description="Notional reset flag, if true the notional of the funding leg is reset at the start of every  coupon to match the value of the equity leg (equity price at start of coupon times quantity).")
    quantity: Union[StrictFloat, StrictInt] = Field(..., description="The quantity or number of shares in the Equity Swap.")
    underlying_identifier: constr(strict=True, min_length=1) = Field(..., alias="underlyingIdentifier", description="External market codes and identifiers for the EquitySwap, e.g. RIC.    Supported string (enumeration) values are: [LusidInstrumentId, Isin, Sedol, Cusip, ClientInternal, Figi, RIC, QuotePermId, REDCode, BBGId, ICECode].")
    equity_swap_dividend_payment_timing: Optional[StrictStr] = Field(None, alias="equitySwapDividendPaymentTiming", description="Determines how the payment of dividends is handled for the equity swap.  Defaults to paying at the next Equity coupon date.                Supported string (enumeration) values are: [PayAtNextEquityCouponDate, PayAtMaturityOfSwap, PayAtNextFundingLegCouponDate, PayAtPaymentDateOfDividendEvent].")
    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")
    additional_properties: Dict[str, Any] = {}
    __properties = ["instrumentType", "startDate", "maturityDate", "code", "equityFlowConventions", "fundingLeg", "includeDividends", "initialPrice", "notionalReset", "quantity", "underlyingIdentifier", "equitySwapDividendPaymentTiming"]

    @validator('instrument_type')
    def instrument_type_validate_enum(cls, value):
        """Validates the enum"""
        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'):
            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')")
        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) -> EquitySwap:
        """Create an instance of EquitySwap 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 equity_flow_conventions
        if self.equity_flow_conventions:
            _dict['equityFlowConventions'] = self.equity_flow_conventions.to_dict()
        # override the default output from pydantic by calling `to_dict()` of funding_leg
        if self.funding_leg:
            _dict['fundingLeg'] = self.funding_leg.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 equity_swap_dividend_payment_timing (nullable) is None
        # and __fields_set__ contains the field
        if self.equity_swap_dividend_payment_timing is None and "equity_swap_dividend_payment_timing" in self.__fields_set__:
            _dict['equitySwapDividendPaymentTiming'] = None

        return _dict

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

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

        _obj = EquitySwap.parse_obj({
            "instrument_type": obj.get("instrumentType"),
            "start_date": obj.get("startDate"),
            "maturity_date": obj.get("maturityDate"),
            "code": obj.get("code"),
            "equity_flow_conventions": FlowConventions.from_dict(obj.get("equityFlowConventions")) if obj.get("equityFlowConventions") is not None else None,
            "funding_leg": InstrumentLeg.from_dict(obj.get("fundingLeg")) if obj.get("fundingLeg") is not None else None,
            "include_dividends": obj.get("includeDividends"),
            "initial_price": obj.get("initialPrice"),
            "notional_reset": obj.get("notionalReset"),
            "quantity": obj.get("quantity"),
            "underlying_identifier": obj.get("underlyingIdentifier"),
            "equity_swap_dividend_payment_timing": obj.get("equitySwapDividendPaymentTiming")
        })
        # 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
