from random import randint

from mona_sdk import Client, MonaSingleMessage

# Importing Modules
import random
import calendar
import time

# Use 'conda install shapely' to import the shapely library.
from shapely.geometry import Polygon, Point

# Es monitor test
from mona_sdk.geo_util import get_tile_bounding_box, get_geojson_from_zxy

client_id = "e8018061-0559-4b22-b041-f10ef5848cd6"
secret_key = "9df5eefb-de6d-4529-b79a-60b398353449"
# Let's have 4 context classes - the 4th will take the default value (0.7).
my_mona_client = Client(
    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",
    # sampling_config_name="smadar_neti_test",
    raise_export_exceptions=True,
    raise_service_exceptions=True
)


def polygon_random_points(poly, num_points):
    min_x, min_y, max_x, max_y = poly.bounds
    points = []
    while len(points) < num_points:
        random_point = Point(
            [random.uniform(min_x, max_x), random.uniform(min_y, max_y)]
        )
        if random_point.within(poly):
            points.append(random_point)
    return points


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


def get_random_0_to_180():
    ret = random_with_N_digits(3)
    return ret % 180


def get_random_0_to_minus180():
    return -get_random_0_to_180()


def get_random_from_0_to_90():
    ret = random_with_N_digits(2)
    return ret % 90


def get_random_from_0_to_minus90():
    return -get_random_from_0_to_90()


tiles = ["7/72/127", "7/59/49", "7/0/1", "7/70/42", "7/40/58", "7/32/50", "7/0/0", "7/2/2", "7/0/1"]
anoraml_tile = "7/7/7"
polygons_normal = [
    Polygon(get_geojson_from_zxy(tile)["coordinates"][0]) for tile in tiles
]
polygons_anormal = [Polygon(get_geojson_from_zxy(anoraml_tile)["coordinates"][0])]

NUMBER_OF_DAYS_TO_SEND_BACK_FROM_NOW = 14
NUMBER_OF_POINTS_PER_TILE = 100
# This goes from now and back and send data for each day...
DELTA_TIME_DAY = 86400
current_timestamp = 1674054671#calendar.timegm(time.gmtime())


messages = []

for i in range(NUMBER_OF_DAYS_TO_SEND_BACK_FROM_NOW):
    current_timestamp -= DELTA_TIME_DAY
    print(f"sending data for timestamp {current_timestamp}")
    # Choose the number of points desired. This example uses 20 points.
    points = []
    points_anormal = []
    for polygon in polygons_normal:
        points += polygon_random_points(polygon, NUMBER_OF_POINTS_PER_TILE)
    for polygon in polygons_anormal:
        points_anormal += polygon_random_points(polygon, NUMBER_OF_POINTS_PER_TILE)

    for point in points:
        messages.append(
            MonaSingleMessage(
                message={
                    "geo_test_point_str":  {
                        "lat": point.y,
                        "lon": point.x,
                    },
                    "number_to_average_outlier_with": randint(0, 100),
                    "on_camera": random.choice([False]),
                    "on_microphone": random.choice([True, False]),
                },
                contextClass="context_class_name",
                contextId=str(
                    random_with_N_digits(9)
                ),  # str(random_with_N_digits(10)),
                exportTimestamp=current_timestamp,
            )
        )
    for point in points_anormal:
        messages.append(
            MonaSingleMessage(
                message={
                    "geo_test_point_str": {
                        "lat": point.y,
                        "lon": point.x,
                    },
                    "number_to_average_outlier_with": randint(2000, 2500),
                    "on_camera": random.choice([True]),
                    "on_microphone": random.choice([True, False]),
                },
                contextClass="context_class_name",
                contextId=str(
                    random_with_N_digits(9)
                ),  # str(random_with_N_digits(10)),
                exportTimestamp=current_timestamp,
            )
        )

    print(f"sending context_class context_class_name")
    succeed_to_export = my_mona_client.export_batch(messages)
    print(succeed_to_export)
    messages = []
    # print(f"\n{context_class}: {succeed_to_export}")
