# 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.bond_conversion_entry import BondConversionEntry
from lusid.models.schedule import Schedule

class BondConversionSchedule(Schedule):
    """
    A BondConversionSchedule object represents a class containing the  information required for the creation of convertible features in a ComplexBond  # noqa: E501
    """
    identifiers: Optional[Dict[str, Optional[StrictStr]]] = Field(default=None, description="The market identifier(s) of the share that the bond converts to. The instrument  will not fail validation if no identifier is supplied.")
    bond_conversion_entries: Optional[List[BondConversionEntry]] = Field(default=None, description="The dates at which the bond may be converted and associated information required about the conversion.", alias="bondConversionEntries")
    conversion_trigger:  StrictStr = Field(...,alias="conversionTrigger", description="Corporate event that triggers a conversion    Supported string (enumeration) values are: [NextEquityFinancing, IpoConversion, KnownDates, SoftCall].") 
    delivery_type:  Optional[StrictStr] = Field(None,alias="deliveryType", description="Is a conversion made into cash or into shares?  Defaults to \"Physical\" if not set.    Supported string (enumeration) values are: [Cash, Physical].") 
    exercise_type:  StrictStr = Field(...,alias="exerciseType", description="The exercise type of the conversion schedule (American or European).  For American type, the bond is convertible from a given exercise date until the next date in the schedule, or until it matures.  For European type, the bond is only convertible on the given exercise date.    Supported string (enumeration) values are: [European, Bermudan, American].") 
    includes_accrued: Optional[StrictBool] = Field(default=None, description="Set this to true if a accrued interest is included in the conversion. Defaults to true.", alias="includesAccrued")
    mandatory_conversion: Optional[StrictBool] = Field(default=None, description="Set this to true if a conversion is mandatory if the trigger occurs. Defaults to false.", alias="mandatoryConversion")
    notification_period_end: Optional[datetime] = Field(default=None, description="The last day in the notification period for the conversion of the bond", alias="notificationPeriodEnd")
    notification_period_start: Optional[datetime] = Field(default=None, description="The first day in the notification period for the conversion of the bond", alias="notificationPeriodStart")
    schedule_type:  StrictStr = Field(...,alias="scheduleType", description="The available values are: FixedSchedule, FloatSchedule, OptionalitySchedule, StepSchedule, Exercise, FxRateSchedule, FxLinkedNotionalSchedule, BondConversionSchedule, Invalid") 
    additional_properties: Dict[str, Any] = {}
    __properties = ["scheduleType", "identifiers", "bondConversionEntries", "conversionTrigger", "deliveryType", "exerciseType", "includesAccrued", "mandatoryConversion", "notificationPeriodEnd", "notificationPeriodStart"]

    @validator('schedule_type')
    def schedule_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 'BondConversionSchedule' 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 "schedule_type" != "type":
            return value

        if value not in ['FixedSchedule', 'FloatSchedule', 'OptionalitySchedule', 'StepSchedule', 'Exercise', 'FxRateSchedule', 'FxLinkedNotionalSchedule', 'BondConversionSchedule', 'Invalid']:
            raise ValueError("must be one of enum values ('FixedSchedule', 'FloatSchedule', 'OptionalitySchedule', 'StepSchedule', 'Exercise', 'FxRateSchedule', 'FxLinkedNotionalSchedule', 'BondConversionSchedule', 'Invalid')")
        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) -> BondConversionSchedule:
        """Create an instance of BondConversionSchedule 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 each item in bond_conversion_entries (list)
        _items = []
        if self.bond_conversion_entries:
            for _item in self.bond_conversion_entries:
                if _item:
                    _items.append(_item.to_dict())
            _dict['bondConversionEntries'] = _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

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

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

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

        return _dict

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

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

        _obj = BondConversionSchedule.parse_obj({
            "schedule_type": obj.get("scheduleType"),
            "identifiers": obj.get("identifiers"),
            "bond_conversion_entries": [BondConversionEntry.from_dict(_item) for _item in obj.get("bondConversionEntries")] if obj.get("bondConversionEntries") is not None else None,
            "conversion_trigger": obj.get("conversionTrigger"),
            "delivery_type": obj.get("deliveryType"),
            "exercise_type": obj.get("exerciseType"),
            "includes_accrued": obj.get("includesAccrued"),
            "mandatory_conversion": obj.get("mandatoryConversion"),
            "notification_period_end": obj.get("notificationPeriodEnd"),
            "notification_period_start": obj.get("notificationPeriodStart")
        })
        # 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

BondConversionSchedule.update_forward_refs()
