import threading
import time
from spotflow_device import DesiredProperties, DeviceClient

DEFAULT_SPEED = 10

# Properties are protected with a lock, because the callback is executed from a background thread.
properties_lock = threading.Lock()

properties = {
    "settings": {
        "speed": DEFAULT_SPEED
    },
    "status": {
        "lastMaintenance": "2024-02-04"
    }
}

# Keep configuration in sync using a callback
def desired_properties_updated_callback(desired_properties: DesiredProperties) -> None:
    global client, properties_lock, properties, desired_properties_updated
    with properties_lock:
        print(f"[Callback] Received Desired Properties (version {desired_properties.version}): {desired_properties.values}")

        if 'settings' in desired_properties.values and 'speed' in desired_properties.values['settings']:
            print("[Callback] Updating the speed to {}".format(desired_properties.values['settings']['speed']))
            properties['settings']['speed'] = desired_properties.values['settings']['speed']

        print("[Callback] Updating Reported Properties")
        client.update_reported_properties(properties)

# Connect to the Platform
with properties_lock:                       # Without the lock, the callback might be executed before the global client variable is set
    client = DeviceClient.start(device_id="robo-arm", provisioning_token="<Your Provisioning Token>", db="spotf_robo-arm.db",
                                desired_properties_updated_callback=desired_properties_updated_callback)

while True:
    with properties_lock:
        print("Current speed: {}".format(properties['settings']['speed']))

    time.sleep(5)
