# 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, List, Optional, Union
from pydantic.v1 import BaseModel, Field, StrictFloat, StrictInt, StrictStr, conlist, constr, validator
from lusid.models.day_month import DayMonth
from lusid.models.link import Link
from lusid.models.model_property import ModelProperty
from lusid.models.resource_id import ResourceId
from lusid.models.version import Version

class Fee(BaseModel):
    """
    Fee
    """
    href: Optional[StrictStr] = Field(None, description="The specific Uniform Resource Identifier (URI) for this resource at the requested effective and asAt datetime.")
    fee_code: Optional[constr(strict=True, max_length=64, min_length=1)] = Field(None, alias="feeCode", description="The code of the Fee.")
    fee_type_id: ResourceId = Field(..., alias="feeTypeId")
    display_name: constr(strict=True, max_length=50, min_length=0) = Field(..., alias="displayName", description="The name of the Fee.")
    description: Optional[constr(strict=True, max_length=1024, min_length=0)] = Field(None, description="A description for the Fee.")
    origin: Optional[constr(strict=True, max_length=512, min_length=1)] = Field(None, description="The origin or source of the Fee accrual.")
    calculation_base: Optional[constr(strict=True, max_length=1024, min_length=0)] = Field(None, alias="calculationBase", description="The calculation base for a Fee that is calculated using a percentage (TotalAnnualAccrualAmount and CalculationBase cannot both be present). When the Fee is a ShareClass Fee (i.e: when ShareClasses contains at least one value), each of the following would be a valid CalculationBase: \"10000.00\", \"ShareClass.GAV\", \"ShareClass.GAV - ShareClass.Fees[ShareClassFeeCode1].Amount\", \"ShareClass.Fees[ShareClassFeeCode1].CalculationBase\". When the Fee is a NonShareClassSpecific Fee (i.e: when ShareClasses contains no values), each of the following would be a valid CalculationBase: \"10000.00\", \"GAV\", \"GAV - Fees[NonClassSpecificFeeCode1].Amount\", \"Fees[NonClassSpecificFeeCode1].CalculationBase\". ")
    accrual_currency: constr(strict=True, max_length=3, min_length=0) = Field(..., alias="accrualCurrency", description="The accrual currency.")
    treatment: constr(strict=True, min_length=1) = Field(..., description="The accrual period of the Fee; 'Monthly' or 'Daily'.")
    total_annual_accrual_amount: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="totalAnnualAccrualAmount", description="The total annual accrued amount for the Fee. (TotalAnnualAccrualAmount and CalculationBase cannot both be present)")
    fee_rate_percentage: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="feeRatePercentage", description="The fee rate percentage. (Required when CalculationBase is present and not compatible with TotalAnnualAccrualAmount)")
    payable_frequency: constr(strict=True, min_length=1) = Field(..., alias="payableFrequency", description="The payable frequency for the Fee; 'Annually', 'Quarterly' or 'Monthly'.")
    business_day_convention: constr(strict=True, min_length=1) = Field(..., alias="businessDayConvention", description="The business day convention to use for Fee calculations on weekends or holidays. Supported string values are: [Previous, P, Following, F, None].")
    start_date: datetime = Field(..., alias="startDate", description="The start date of the Fee.")
    end_date: Optional[datetime] = Field(None, alias="endDate", description="The end date of the Fee.")
    anchor_date: Optional[DayMonth] = Field(None, alias="anchorDate")
    properties: Optional[Dict[str, ModelProperty]] = Field(None, description="The Fee properties. These will be from the 'Fee' domain.")
    version: Optional[Version] = None
    portfolio_id: Optional[ResourceId] = Field(None, alias="portfolioId")
    share_classes: Optional[conlist(StrictStr)] = Field(None, alias="shareClasses", description="The short codes of the ShareClasses that the Fee should be applied to. Optional: if this is null or empty, then the Fee will be divided between all the ShareClasses of the Fund according to the capital ratio.")
    links: Optional[conlist(Link)] = None
    __properties = ["href", "feeCode", "feeTypeId", "displayName", "description", "origin", "calculationBase", "accrualCurrency", "treatment", "totalAnnualAccrualAmount", "feeRatePercentage", "payableFrequency", "businessDayConvention", "startDate", "endDate", "anchorDate", "properties", "version", "portfolioId", "shareClasses", "links"]

    @validator('fee_code')
    def fee_code_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^[a-zA-Z0-9\-_]+$", value):
            raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9\-_]+$/")
        return value

    @validator('description')
    def description_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^[\s\S]*$", value):
            raise ValueError(r"must validate the regular expression /^[\s\S]*$/")
        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) -> Fee:
        """Create an instance of Fee 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={
                          },
                          exclude_none=True)
        # override the default output from pydantic by calling `to_dict()` of fee_type_id
        if self.fee_type_id:
            _dict['feeTypeId'] = self.fee_type_id.to_dict()
        # override the default output from pydantic by calling `to_dict()` of anchor_date
        if self.anchor_date:
            _dict['anchorDate'] = self.anchor_date.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each value in properties (dict)
        _field_dict = {}
        if self.properties:
            for _key in self.properties:
                if self.properties[_key]:
                    _field_dict[_key] = self.properties[_key].to_dict()
            _dict['properties'] = _field_dict
        # override the default output from pydantic by calling `to_dict()` of version
        if self.version:
            _dict['version'] = self.version.to_dict()
        # override the default output from pydantic by calling `to_dict()` of portfolio_id
        if self.portfolio_id:
            _dict['portfolioId'] = self.portfolio_id.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in links (list)
        _items = []
        if self.links:
            for _item in self.links:
                if _item:
                    _items.append(_item.to_dict())
            _dict['links'] = _items
        # set to None if href (nullable) is None
        # and __fields_set__ contains the field
        if self.href is None and "href" in self.__fields_set__:
            _dict['href'] = None

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

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

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

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

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

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

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

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

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

        return _dict

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

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

        _obj = Fee.parse_obj({
            "href": obj.get("href"),
            "fee_code": obj.get("feeCode"),
            "fee_type_id": ResourceId.from_dict(obj.get("feeTypeId")) if obj.get("feeTypeId") is not None else None,
            "display_name": obj.get("displayName"),
            "description": obj.get("description"),
            "origin": obj.get("origin"),
            "calculation_base": obj.get("calculationBase"),
            "accrual_currency": obj.get("accrualCurrency"),
            "treatment": obj.get("treatment"),
            "total_annual_accrual_amount": obj.get("totalAnnualAccrualAmount"),
            "fee_rate_percentage": obj.get("feeRatePercentage"),
            "payable_frequency": obj.get("payableFrequency"),
            "business_day_convention": obj.get("businessDayConvention"),
            "start_date": obj.get("startDate"),
            "end_date": obj.get("endDate"),
            "anchor_date": DayMonth.from_dict(obj.get("anchorDate")) if obj.get("anchorDate") is not None else None,
            "properties": dict(
                (_k, ModelProperty.from_dict(_v))
                for _k, _v in obj.get("properties").items()
            )
            if obj.get("properties") is not None
            else None,
            "version": Version.from_dict(obj.get("version")) if obj.get("version") is not None else None,
            "portfolio_id": ResourceId.from_dict(obj.get("portfolioId")) if obj.get("portfolioId") is not None else None,
            "share_classes": obj.get("shareClasses"),
            "links": [Link.from_dict(_item) for _item in obj.get("links")] if obj.get("links") is not None else None
        })
        return _obj
