import asyncio
import json
import time
from concurrent.futures import ThreadPoolExecutor

from mona_sdk import MonaSingleMessage
from mona_sdk.async_client import AsyncClient


async def methods_test():
    client_id = "40c08ee6-f411-41b1-9752-80d98897aae6"
    secret_key = "5694fad0-e372-488e-89cf-22ed8693a5a2"
    user_id = "01971934-5acd-4888-9894-071e32fa867c"
    loop = asyncio.get_event_loop()

    with ThreadPoolExecutor(max_workers=1) as executor:

        async_client = AsyncClient(
            client_id, secret_key, user_id=user_id, event_loop=loop, executor=executor
        )

        print("Starting test ...")

        # is_active
        is_active = await async_client.is_active_async()
        print(f"is_active: {is_active}")

        # sampling factors
        sampling_factors = await async_client.get_sampling_factors_async()
        print(f"sampling_factors: {sampling_factors}")
        events = {
            "userId": user_id,
            "messages": [
                {
                    "arcClass": "arcClassName",
                    "contextId": "ID_123",
                    "message": {
                        "company-id": "79sg7723-0253438g3453",
                        "browser": "chrome",
                        "text_length": 50,
                        "top_tagged_brand": "adidas",
                    },
                },
                {
                    "arcClass": "arcClassName",
                    "contextId": "ID_123",
                    "message": {"coutry": "usa"},
                },
                {
                    "arcClass": "arcClassName",
                    "contextId": "ID_124",
                    "message": {
                        "company-id": "2435f32-02ve3538g5232",
                        "browser": "safari",
                        "text_length": 30,
                        "top_tagged_brand": "nike",
                    },
                },
            ],
        }
        suggested_config = (
            await async_client.get_suggested_config_from_user_input_async(events, event_loop=loop, executor=executor)
        )
        print(f"suggested_config: {suggested_config}")
        mona_messages = [
            MonaSingleMessage(
                message={"smadar_test": "1"},
                contextClass="SMADAR_TEST2",
                contextId="903c97aagfd6812b4c8e32fa",
            ),
            MonaSingleMessage(
                message={"smadar_test": "2"},
                contextClass="SMADAR_TEST1",
                contextId="903c97aagfd6812b48gj27df",
            ),
            MonaSingleMessage(
                message={"smadar_test": "3"},
                contextClass="SMADAR_TEST1",
            ),
            MonaSingleMessage(
                message={"smadar_test": "4"},
                contextClass="SMADAR_TEST_NOT_IN_SAMPLING_CONFIG",
            ),
            MonaSingleMessage(
                message={"smadar_test": "5"},
                contextClass="SMADAR_TEST_NOT_IN_SAMPLING_CONFIG",
                contextId="10jjf8e4gfd681204j38f7gb",
            ),
        ]
        # export (Single msg)
        #export_res = await async_client.export_async(mona_messages[0])
        #print(f"export res: {export_res}")
        # export batch
        #export_batch_res = await async_client.export_batch_async(mona_messages)
        #print(f"export batch res: {export_batch_res}")

        config = async_client.get_config()
        print(f"get_config res: {config}")

        res = async_client.validate_config(config)
        print(f"validate_config res: {res}")

        if (
            config["01971934-5acd-4888-9894-071e32fa867c"]["LOAN_APPLICATION_TUTORIAL"][
                "fields"
            ]["feature_9"]["segmentations"]["original"]["bucket_size"]
            == 200
        ):
            config["01971934-5acd-4888-9894-071e32fa867c"]["LOAN_APPLICATION_TUTORIAL"][
                "fields"
            ]["feature_9"]["segmentations"]["original"]["bucket_size"] = 100
        else:
            config["01971934-5acd-4888-9894-071e32fa867c"]["LOAN_APPLICATION_TUTORIAL"][
                "fields"
            ]["feature_9"]["segmentations"]["original"]["bucket_size"] = 200

        # upload_config
        res = await async_client.upload_config_async(
            config, commit_message="smadar async test", author="smadar"
        )
        print(res)
        context_class_config = config["01971934-5acd-4888-9894-071e32fa867c"]["TEST"]

        if (
            context_class_config["fields"]["approved_amount"]["segmentations"][
                "new_default"
            ]["bucket_size"]
            == 10000
        ):
            context_class_config["fields"]["approved_amount"]["segmentations"][
                "new_default"
            ]["bucket_size"] = (10000 / 2)
        else:
            context_class_config["fields"]["approved_amount"]["segmentations"][
                "new_default"
            ]["bucket_size"] = 10000

        # Upload_config_per_context_class
        res = await async_client.upload_config_per_context_class_async(
            author="smadar",
            commit_message="smadar async test",
            context_class="TEST",
            config=context_class_config,
        )
        print(res)

        res = await async_client.get_config_history_async()
        print(res)

        # create_sampling_factor()
        # res = await async_client.create_sampling_factor_async(config_name="smadar_test", sampling_factors=)

        # get_insights
        res = await async_client.get_insights_async(
            context_class="LOAN_APPLICATION_TUTORIAL", min_segment_size=0
        )
        print(res)
        # res = get_ingested_data_for_a_specific_segment_async(context_class,start_time,end_time,segment,excluded_segments=UNPROVIDED_VALUE)
        # get_aggregated_data_of_a_specific_segment(
        #    self,
        #    context_class,
        #    timestamp_from,
        #    timestamp_to,
        #    time_series_resolutions=UNPROVIDED_VALUE,
        #    with_histogram=UNPROVIDED_VALUE,
        #    time_zone=UNPROVIDED_VALUE,
        #    metrics=UNPROVIDED_VALUE,
        #    requested_segments=UNPROVIDED_VALUE,
        #    excluded_segments=UNPROVIDED_VALUE,
        #    baseline_segment=UNPROVIDED_VALUE,
        # )

        # def get_aggregated_stats_of_a_specific_segmentation(
        #        self,
        #        context_class,
        #        dimension,
        #        target_time_range,
        #        compared_time_range,
        #        metric_1_field,
        #        metric_2_field,
        #        metric_1_type,
        #        metric_2_type,
        #        min_segment_size,
        #        sort_function,
        #        baseline_segment=UNPROVIDED_VALUE,
        #        excluded_segments=UNPROVIDED_VALUE,
        #        target_segments_filter=UNPROVIDED_VALUE,
        #        compared_segments_filter=UNPROVIDED_VALUE,
        # )
    print("... Done!")


#asyncio.run(methods_test())
from random import randint

# Es monitor test
client_id = "e8018061-0559-4b22-b041-f10ef5848cd6"
secret_key = "9df5eefb-de6d-4529-b79a-60b398353449"

CONTEXT_CLASSES = [
    "SMADAR_TEST_IN_CONFIG_SAMPLED",
    "SMADAR_TEST_IN_CONFIG_SAMPLED_NOT_TAKEN",
    "SMADAR_TEST_TAKES_DEFAULT",
    "SMADAR_TEST_IN_CONFIG_FULLY_TAKEN",
    "ANOTHER_CONTEXT",
    "SOME_OTHER_CONTEXT",
]
NUMBER_OF_MESSAGES_PER_CONTEXT_CLASS = 10000


def random_with_N_digits(n):
    range_start = 10 ** (n - 1)
    range_end = (10 ** n) - 1
    return randint(range_start, range_end)


async def time_test():
    mona_client = AsyncClient(
        api_key=client_id,
        secret=secret_key,
        user_id="ef3a7c1a-cf94-489b-8c69-5075136003f2",
        # should_use_authentication=False,
        # should_use_ssl=False,
        # override_rest_api_host="rest-api host address",
    )
    coroutines = []
    messages_list = []
    for context_class in CONTEXT_CLASSES:
        messages = []
        for i in range(NUMBER_OF_MESSAGES_PER_CONTEXT_CLASS):
            messages.append(
                MonaSingleMessage(
                    message={"sampled": i},
                    contextClass=context_class,
                    contextId=str(random_with_N_digits(10)),
                )
            )
        messages_list.append(messages)
    start_time = time.time()
    for messages in messages_list:
        coroutines.append(asyncio.create_task(mona_client.export_batch_async(messages)))
    #original_pokemon = await asyncio.gather(*coroutines)
    print("--- %s seconds ---" % (time.time() - start_time))



#asyncio.run(methods_test())


#start_time = time.time()

asyncio.run(time_test())

#print("--- %s seconds ---" % (time.time() - start_time))



