# This file was auto-generated by Fern from our API Definition.

import typing

from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.request_options import RequestOptions
from ...types.create_data_event_request_two import CreateDataEventRequestTwo
from ..types.data_event_summary import DataEventSummary
from .raw_client import AsyncRawDataEventsClient, RawDataEventsClient
from .types.create_data_event_summaries_request_event_summaries import CreateDataEventSummariesRequestEventSummaries
from .types.lis_data_events_request_filter import LisDataEventsRequestFilter

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class DataEventsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawDataEventsClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> RawDataEventsClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawDataEventsClient
        """
        return self._raw_client

    def lis_data_events(
        self,
        *,
        filter: LisDataEventsRequestFilter,
        type: str,
        summary: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DataEventSummary:
        """

        > 🚧
        >
        > Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days

        The events belonging to a customer can be listed by sending a GET request to `https://api.intercom.io/events` with a user or lead identifier along with a `type` parameter. The identifier parameter can be one of `user_id`, `email` or `intercom_user_id`. The `type` parameter value must be `user`.

        - `https://api.intercom.io/events?type=user&user_id={user_id}`
        - `https://api.intercom.io/events?type=user&email={email}`
        - `https://api.intercom.io/events?type=user&intercom_user_id={id}` (this call can be used to list leads)

        The `email` parameter value should be [url encoded](http://en.wikipedia.org/wiki/Percent-encoding) when sending.

        You can optionally define the result page size as well with the `per_page` parameter.

        Parameters
        ----------
        filter : LisDataEventsRequestFilter

        type : str
            The value must be user

        summary : typing.Optional[bool]
            summary flag

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DataEventSummary
            Successful response

        Examples
        --------
        from intercom import Intercom
        from intercom.unstable.data_events import LisDataEventsRequestFilterUserId

        client = Intercom(
            token="YOUR_TOKEN",
        )
        client.unstable.data_events.lis_data_events(
            filter=LisDataEventsRequestFilterUserId(
                user_id="user_id",
            ),
            type="type",
        )
        """
        _response = self._raw_client.lis_data_events(
            filter=filter, type=type, summary=summary, request_options=request_options
        )
        return _response.data

    def create_data_event(
        self, *, request: CreateDataEventRequestTwo, request_options: typing.Optional[RequestOptions] = None
    ) -> None:
        """

        You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a `Content-Type` of `application/json`.

        When using the JavaScript API, [adding the code to your app](http://docs.intercom.io/configuring-Intercom/tracking-user-events-in-your-app) makes the Events API available. Once added, you can submit an event using the `trackEvent` method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event.

        With the Ruby client you pass a hash describing the event to `Intercom::Event.create`, or call the `track_user` method directly on the current user object (e.g. `user.track_event`).

        **NB: For the JSON object types, please note that we do not currently support nested JSON structure.**

        | Type            | Description                                                                                                                                                                                                     | Example                                                                           |
        | :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- |
        | String          | The value is a JSON String                                                                                                                                                                                      | `"source":"desktop"`                                                              |
        | Number          | The value is a JSON Number                                                                                                                                                                                      | `"load": 3.67`                                                                    |
        | Date            | The key ends with the String `_date` and the value is a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time), assumed to be in the [UTC](http://en.wikipedia.org/wiki/Coordinated_Universal_Time) timezone. | `"contact_date": 1392036272`                                                      |
        | Link            | The value is a HTTP or HTTPS URI.                                                                                                                                                                               | `"article": "https://example.org/ab1de.html"`                                     |
        | Rich Link       | The value is a JSON object that contains `url` and `value` keys.                                                                                                                                                | `"article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"}` |
        | Monetary Amount | The value is a JSON object that contains `amount` and `currency` keys. The `amount` key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99.          | `"price": {"amount": 34999, "currency": "eur"}`                                   |

        **Lead Events**

        When submitting events for Leads, you will need to specify the Lead's `id`.

        **Metadata behaviour**

        - We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event.
        - It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one.
        - There might be up to 24 hrs delay when you send a new metadata for an existing event.

        **Event de-duplication**

        The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is **strongly recommended** to send a second granularity Unix timestamp in the `created_at` field.

        Duplicated events are responded to using the normal `202 Accepted` code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place.

        ### HTTP API Responses

        - Successful responses to submitted events return `202 Accepted` with an empty body.
        - Unauthorised access will be rejected with a `401 Unauthorized` or `403 Forbidden` response code.
        - Events sent about users that cannot be found will return a `404 Not Found`.
        - Event lists containing duplicate events will have those duplicates ignored.
        - Server errors will return a `500` response code and may contain an error message in the body.

        Parameters
        ----------
        request : CreateDataEventRequestTwo

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        None

        Examples
        --------
        from intercom import Intercom

        client = Intercom(
            token="YOUR_TOKEN",
        )
        client.unstable.data_events.create_data_event(
            request={"key": "value"},
        )
        """
        _response = self._raw_client.create_data_event(request=request, request_options=request_options)
        return _response.data

    def data_event_summaries(
        self,
        *,
        user_id: typing.Optional[str] = OMIT,
        event_summaries: typing.Optional[CreateDataEventSummariesRequestEventSummaries] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred.

        Parameters
        ----------
        user_id : typing.Optional[str]
            Your identifier for the user.

        event_summaries : typing.Optional[CreateDataEventSummariesRequestEventSummaries]
            A list of event summaries for the user. Each event summary should contain the event name, the time the event occurred, and the number of times the event occurred. The event name should be a past tense 'verb-noun' combination, to improve readability, for example `updated-plan`.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        None

        Examples
        --------
        from intercom import Intercom

        client = Intercom(
            token="YOUR_TOKEN",
        )
        client.unstable.data_events.data_event_summaries()
        """
        _response = self._raw_client.data_event_summaries(
            user_id=user_id, event_summaries=event_summaries, request_options=request_options
        )
        return _response.data


class AsyncDataEventsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawDataEventsClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> AsyncRawDataEventsClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawDataEventsClient
        """
        return self._raw_client

    async def lis_data_events(
        self,
        *,
        filter: LisDataEventsRequestFilter,
        type: str,
        summary: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DataEventSummary:
        """

        > 🚧
        >
        > Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days

        The events belonging to a customer can be listed by sending a GET request to `https://api.intercom.io/events` with a user or lead identifier along with a `type` parameter. The identifier parameter can be one of `user_id`, `email` or `intercom_user_id`. The `type` parameter value must be `user`.

        - `https://api.intercom.io/events?type=user&user_id={user_id}`
        - `https://api.intercom.io/events?type=user&email={email}`
        - `https://api.intercom.io/events?type=user&intercom_user_id={id}` (this call can be used to list leads)

        The `email` parameter value should be [url encoded](http://en.wikipedia.org/wiki/Percent-encoding) when sending.

        You can optionally define the result page size as well with the `per_page` parameter.

        Parameters
        ----------
        filter : LisDataEventsRequestFilter

        type : str
            The value must be user

        summary : typing.Optional[bool]
            summary flag

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DataEventSummary
            Successful response

        Examples
        --------
        import asyncio

        from intercom import AsyncIntercom
        from intercom.unstable.data_events import LisDataEventsRequestFilterUserId

        client = AsyncIntercom(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.unstable.data_events.lis_data_events(
                filter=LisDataEventsRequestFilterUserId(
                    user_id="user_id",
                ),
                type="type",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.lis_data_events(
            filter=filter, type=type, summary=summary, request_options=request_options
        )
        return _response.data

    async def create_data_event(
        self, *, request: CreateDataEventRequestTwo, request_options: typing.Optional[RequestOptions] = None
    ) -> None:
        """

        You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a `Content-Type` of `application/json`.

        When using the JavaScript API, [adding the code to your app](http://docs.intercom.io/configuring-Intercom/tracking-user-events-in-your-app) makes the Events API available. Once added, you can submit an event using the `trackEvent` method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event.

        With the Ruby client you pass a hash describing the event to `Intercom::Event.create`, or call the `track_user` method directly on the current user object (e.g. `user.track_event`).

        **NB: For the JSON object types, please note that we do not currently support nested JSON structure.**

        | Type            | Description                                                                                                                                                                                                     | Example                                                                           |
        | :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- |
        | String          | The value is a JSON String                                                                                                                                                                                      | `"source":"desktop"`                                                              |
        | Number          | The value is a JSON Number                                                                                                                                                                                      | `"load": 3.67`                                                                    |
        | Date            | The key ends with the String `_date` and the value is a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time), assumed to be in the [UTC](http://en.wikipedia.org/wiki/Coordinated_Universal_Time) timezone. | `"contact_date": 1392036272`                                                      |
        | Link            | The value is a HTTP or HTTPS URI.                                                                                                                                                                               | `"article": "https://example.org/ab1de.html"`                                     |
        | Rich Link       | The value is a JSON object that contains `url` and `value` keys.                                                                                                                                                | `"article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"}` |
        | Monetary Amount | The value is a JSON object that contains `amount` and `currency` keys. The `amount` key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99.          | `"price": {"amount": 34999, "currency": "eur"}`                                   |

        **Lead Events**

        When submitting events for Leads, you will need to specify the Lead's `id`.

        **Metadata behaviour**

        - We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event.
        - It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one.
        - There might be up to 24 hrs delay when you send a new metadata for an existing event.

        **Event de-duplication**

        The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is **strongly recommended** to send a second granularity Unix timestamp in the `created_at` field.

        Duplicated events are responded to using the normal `202 Accepted` code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place.

        ### HTTP API Responses

        - Successful responses to submitted events return `202 Accepted` with an empty body.
        - Unauthorised access will be rejected with a `401 Unauthorized` or `403 Forbidden` response code.
        - Events sent about users that cannot be found will return a `404 Not Found`.
        - Event lists containing duplicate events will have those duplicates ignored.
        - Server errors will return a `500` response code and may contain an error message in the body.

        Parameters
        ----------
        request : CreateDataEventRequestTwo

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from intercom import AsyncIntercom

        client = AsyncIntercom(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.unstable.data_events.create_data_event(
                request={"key": "value"},
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.create_data_event(request=request, request_options=request_options)
        return _response.data

    async def data_event_summaries(
        self,
        *,
        user_id: typing.Optional[str] = OMIT,
        event_summaries: typing.Optional[CreateDataEventSummariesRequestEventSummaries] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred.

        Parameters
        ----------
        user_id : typing.Optional[str]
            Your identifier for the user.

        event_summaries : typing.Optional[CreateDataEventSummariesRequestEventSummaries]
            A list of event summaries for the user. Each event summary should contain the event name, the time the event occurred, and the number of times the event occurred. The event name should be a past tense 'verb-noun' combination, to improve readability, for example `updated-plan`.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from intercom import AsyncIntercom

        client = AsyncIntercom(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.unstable.data_events.data_event_summaries()


        asyncio.run(main())
        """
        _response = await self._raw_client.data_event_summaries(
            user_id=user_id, event_summaries=event_summaries, request_options=request_options
        )
        return _response.data
