r"""
    This code was generated by
   ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
    |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
    |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \

    Twilio - Api
    This is the public Twilio REST API.

    NOTE: This class is auto generated by OpenAPI Generator.
    https://openapi-generator.tech
    Do not edit the class manually.
"""

from datetime import date
from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator
from twilio.base import deserialize, serialize, values

from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.version import Version
from twilio.base.page import Page
from twilio.rest.api.v2010.account.usage.record.all_time import AllTimeList
from twilio.rest.api.v2010.account.usage.record.daily import DailyList
from twilio.rest.api.v2010.account.usage.record.last_month import LastMonthList
from twilio.rest.api.v2010.account.usage.record.monthly import MonthlyList
from twilio.rest.api.v2010.account.usage.record.this_month import ThisMonthList
from twilio.rest.api.v2010.account.usage.record.today import TodayList
from twilio.rest.api.v2010.account.usage.record.yearly import YearlyList
from twilio.rest.api.v2010.account.usage.record.yesterday import YesterdayList


class RecordInstance(InstanceResource):
    """
    :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage.
    :ivar api_version: The API version used to create the resource.
    :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT
    :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories).
    :ivar count: The number of usage events, such as the number of calls.
    :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS.
    :ivar description: A plain-language description of the usage category.
    :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`.
    :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account.
    :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`.
    :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`.
    :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources).
    :ivar uri: The URI of the resource, relative to `https://api.twilio.com`.
    :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`.
    :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS.
    """

    def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str):
        super().__init__(version)

        self.account_sid: Optional[str] = payload.get("account_sid")
        self.api_version: Optional[str] = payload.get("api_version")
        self.as_of: Optional[str] = payload.get("as_of")
        self.category: Optional[str] = payload.get("category")
        self.count: Optional[str] = payload.get("count")
        self.count_unit: Optional[str] = payload.get("count_unit")
        self.description: Optional[str] = payload.get("description")
        self.end_date: Optional[date] = deserialize.iso8601_date(
            payload.get("end_date")
        )
        self.price: Optional[float] = deserialize.decimal(payload.get("price"))
        self.price_unit: Optional[str] = payload.get("price_unit")
        self.start_date: Optional[date] = deserialize.iso8601_date(
            payload.get("start_date")
        )
        self.subresource_uris: Optional[Dict[str, object]] = payload.get(
            "subresource_uris"
        )
        self.uri: Optional[str] = payload.get("uri")
        self.usage: Optional[str] = payload.get("usage")
        self.usage_unit: Optional[str] = payload.get("usage_unit")

        self._solution = {
            "account_sid": account_sid,
        }

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        context = " ".join("{}={}".format(k, v) for k, v in self._solution.items())
        return "<Twilio.Api.V2010.RecordInstance {}>".format(context)


class RecordPage(Page):

    def get_instance(self, payload: Dict[str, Any]) -> RecordInstance:
        """
        Build an instance of RecordInstance

        :param payload: Payload response from the API
        """
        return RecordInstance(
            self._version, payload, account_sid=self._solution["account_sid"]
        )

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        return "<Twilio.Api.V2010.RecordPage>"


class RecordList(ListResource):

    def __init__(self, version: Version, account_sid: str):
        """
        Initialize the RecordList

        :param version: Version that contains the resource
        :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read.

        """
        super().__init__(version)

        # Path Solution
        self._solution = {
            "account_sid": account_sid,
        }
        self._uri = "/Accounts/{account_sid}/Usage/Records.json".format(
            **self._solution
        )

        self._all_time: Optional[AllTimeList] = None
        self._daily: Optional[DailyList] = None
        self._last_month: Optional[LastMonthList] = None
        self._monthly: Optional[MonthlyList] = None
        self._this_month: Optional[ThisMonthList] = None
        self._today: Optional[TodayList] = None
        self._yearly: Optional[YearlyList] = None
        self._yesterday: Optional[YesterdayList] = None

    def stream(
        self,
        category: Union[str, object] = values.unset,
        start_date: Union[date, object] = values.unset,
        end_date: Union[date, object] = values.unset,
        include_subaccounts: Union[bool, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> Iterator[RecordInstance]:
        """
        Streams RecordInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved.
        :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date.
        :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`.  You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date.
        :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account.
        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        """
        limits = self._version.read_limits(limit, page_size)
        page = self.page(
            category=category,
            start_date=start_date,
            end_date=end_date,
            include_subaccounts=include_subaccounts,
            page_size=limits["page_size"],
        )

        return self._version.stream(page, limits["limit"])

    async def stream_async(
        self,
        category: Union[str, object] = values.unset,
        start_date: Union[date, object] = values.unset,
        end_date: Union[date, object] = values.unset,
        include_subaccounts: Union[bool, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> AsyncIterator[RecordInstance]:
        """
        Asynchronously streams RecordInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved.
        :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date.
        :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`.  You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date.
        :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account.
        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        """
        limits = self._version.read_limits(limit, page_size)
        page = await self.page_async(
            category=category,
            start_date=start_date,
            end_date=end_date,
            include_subaccounts=include_subaccounts,
            page_size=limits["page_size"],
        )

        return self._version.stream_async(page, limits["limit"])

    def list(
        self,
        category: Union[str, object] = values.unset,
        start_date: Union[date, object] = values.unset,
        end_date: Union[date, object] = values.unset,
        include_subaccounts: Union[bool, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> List[RecordInstance]:
        """
        Lists RecordInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved.
        :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date.
        :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`.  You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date.
        :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account.
        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: list that will contain up to limit results
        """
        return list(
            self.stream(
                category=category,
                start_date=start_date,
                end_date=end_date,
                include_subaccounts=include_subaccounts,
                limit=limit,
                page_size=page_size,
            )
        )

    async def list_async(
        self,
        category: Union[str, object] = values.unset,
        start_date: Union[date, object] = values.unset,
        end_date: Union[date, object] = values.unset,
        include_subaccounts: Union[bool, object] = values.unset,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> List[RecordInstance]:
        """
        Asynchronously lists RecordInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved.
        :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date.
        :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`.  You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date.
        :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account.
        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: list that will contain up to limit results
        """
        return [
            record
            async for record in await self.stream_async(
                category=category,
                start_date=start_date,
                end_date=end_date,
                include_subaccounts=include_subaccounts,
                limit=limit,
                page_size=page_size,
            )
        ]

    def page(
        self,
        category: Union[str, object] = values.unset,
        start_date: Union[date, object] = values.unset,
        end_date: Union[date, object] = values.unset,
        include_subaccounts: Union[bool, object] = values.unset,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> RecordPage:
        """
        Retrieve a single page of RecordInstance records from the API.
        Request is executed immediately

        :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved.
        :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date.
        :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`.  You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date.
        :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account.
        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: Page of RecordInstance
        """
        data = values.of(
            {
                "Category": category,
                "StartDate": serialize.iso8601_date(start_date),
                "EndDate": serialize.iso8601_date(end_date),
                "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts),
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})

        headers["Accept"] = "application/json"

        response = self._version.page(
            method="GET", uri=self._uri, params=data, headers=headers
        )
        return RecordPage(self._version, response, self._solution)

    async def page_async(
        self,
        category: Union[str, object] = values.unset,
        start_date: Union[date, object] = values.unset,
        end_date: Union[date, object] = values.unset,
        include_subaccounts: Union[bool, object] = values.unset,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> RecordPage:
        """
        Asynchronously retrieve a single page of RecordInstance records from the API.
        Request is executed immediately

        :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved.
        :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date.
        :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`.  You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date.
        :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account.
        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: Page of RecordInstance
        """
        data = values.of(
            {
                "Category": category,
                "StartDate": serialize.iso8601_date(start_date),
                "EndDate": serialize.iso8601_date(end_date),
                "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts),
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})

        headers["Accept"] = "application/json"

        response = await self._version.page_async(
            method="GET", uri=self._uri, params=data, headers=headers
        )
        return RecordPage(self._version, response, self._solution)

    def get_page(self, target_url: str) -> RecordPage:
        """
        Retrieve a specific page of RecordInstance records from the API.
        Request is executed immediately

        :param target_url: API-generated URL for the requested results page

        :returns: Page of RecordInstance
        """
        response = self._version.domain.twilio.request("GET", target_url)
        return RecordPage(self._version, response, self._solution)

    async def get_page_async(self, target_url: str) -> RecordPage:
        """
        Asynchronously retrieve a specific page of RecordInstance records from the API.
        Request is executed immediately

        :param target_url: API-generated URL for the requested results page

        :returns: Page of RecordInstance
        """
        response = await self._version.domain.twilio.request_async("GET", target_url)
        return RecordPage(self._version, response, self._solution)

    @property
    def all_time(self) -> AllTimeList:
        """
        Access the all_time
        """
        if self._all_time is None:
            self._all_time = AllTimeList(
                self._version, account_sid=self._solution["account_sid"]
            )
        return self._all_time

    @property
    def daily(self) -> DailyList:
        """
        Access the daily
        """
        if self._daily is None:
            self._daily = DailyList(
                self._version, account_sid=self._solution["account_sid"]
            )
        return self._daily

    @property
    def last_month(self) -> LastMonthList:
        """
        Access the last_month
        """
        if self._last_month is None:
            self._last_month = LastMonthList(
                self._version, account_sid=self._solution["account_sid"]
            )
        return self._last_month

    @property
    def monthly(self) -> MonthlyList:
        """
        Access the monthly
        """
        if self._monthly is None:
            self._monthly = MonthlyList(
                self._version, account_sid=self._solution["account_sid"]
            )
        return self._monthly

    @property
    def this_month(self) -> ThisMonthList:
        """
        Access the this_month
        """
        if self._this_month is None:
            self._this_month = ThisMonthList(
                self._version, account_sid=self._solution["account_sid"]
            )
        return self._this_month

    @property
    def today(self) -> TodayList:
        """
        Access the today
        """
        if self._today is None:
            self._today = TodayList(
                self._version, account_sid=self._solution["account_sid"]
            )
        return self._today

    @property
    def yearly(self) -> YearlyList:
        """
        Access the yearly
        """
        if self._yearly is None:
            self._yearly = YearlyList(
                self._version, account_sid=self._solution["account_sid"]
            )
        return self._yearly

    @property
    def yesterday(self) -> YesterdayList:
        """
        Access the yesterday
        """
        if self._yesterday is None:
            self._yesterday = YesterdayList(
                self._version, account_sid=self._solution["account_sid"]
            )
        return self._yesterday

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        return "<Twilio.Api.V2010.RecordList>"
